问:
What is the difference between using comma and dot specifying decimal numbers?
Hello I am trying to make a simple calculator in vb.net but I have little problem. The problem is when I added double numbers each other such as 4.3+1. When I use dot for double numbers like that --> 4.3 it works perfectly. But when I use comma to specify double such as --> 4,3 it doesn't work.It reads the number like 43 not the 4,3 Here is my code:

```<code>Label3.Text = Val(CDbl(TextBox1.Text)) + Val(CDbl(TextBox2.Text))
            Label3.Text = TextBox1.Text & " + " & TextBox2.Text & " = " & Label3.Text
</code>```

pic1
pic2

答:
The reason this is happening is that the CDbl function will parse around commas as though they were visual delimiters for long numbers. Take this for example:

```<code>Sub Main
    Dim val = "3,000"
    Dim dVal = CDbl(val)
    Console.WriteLine(dVal) ' Outputs 3000
End Sub
</code>```

Unless you know for certain that commas will always be used as a decimal value you wouldn't be able to determine whether or not this is the number 3.000 or 3000

You could replace the ,s in your text with .s, like so:

```<code>Sub Main
    Dim val = "3,000"
    Dim dVal = CDbl(val.Replace(",","."))
    Console.WriteLine(dVal) ' Outputs 3
End Sub
</code>```

This will, however, fail as soon as someone tries to enter a number like 3,000,000

Alternatively, if you happen to know the culture you'll be parsing for ahead of time, you can do something like this.

```<code>Sub Main
    Dim val = "3,000,000.00"
    Dim deVal = "3.000.000,00"
    Console.WriteLine(Double.Parse(val)) ' Outputs 3000000
    Console.WriteLine(Double.Parse(deVal, New System.Globalization.CultureInfo("de-DE"))) ' Outputs 3000000
End Sub
</code>```

The current culture for the machine is used in the first Parse, which in my case is "en-US". By specifically using the "de-DE" culture, the Parse handles the alternative number style.

Body:
Hello I am trying to make a simple calculator in vb.net but I have little problem. The problem is when I added double numbers each other such as 4.3+1. When I use dot for double numbers like that --> 4.3 it works perfectly. But when I use comma to specify double such as --> 4,3 it doesn't work.It reads the number like 43 not the 4,3 Here is my code:

Label3.Text = Val(CDbl(TextBox1.Text)) + Val(CDbl(TextBox2.Text))
            Label3.Text = TextBox1.Text & " + " & TextBox2.Text & " = " & Label3.Text

pic1
pic2

Body:
The reason this is happening is that the CDbl function will parse around commas as though they were visual delimiters for long numbers. Take this for example:

Sub Main
    Dim val = "3,000"
    Dim dVal = CDbl(val)
    Console.WriteLine(dVal) ' Outputs 3000
End Sub

Unless you know for certain that commas will always be used as a decimal value you wouldn't be able to determine whether or not this is the number 3.000 or 3000

You could replace the ,s in your text with .s, like so:

Sub Main
    Dim val = "3,000"
    Dim dVal = CDbl(val.Replace(",","."))
    Console.WriteLine(dVal) ' Outputs 3
End Sub

This will, however, fail as soon as someone tries to enter a number like 3,000,000

Alternatively, if you happen to know the culture you'll be parsing for ahead of time, you can do something like this.

Sub Main
    Dim val = "3,000,000.00"
    Dim deVal = "3.000.000,00"
    Console.WriteLine(Double.Parse(val)) ' Outputs 3000000
    Console.WriteLine(Double.Parse(deVal, New System.Globalization.CultureInfo("de-DE"))) ' Outputs 3000000
End Sub

The current culture for the machine is used in the first Parse, which in my case is "en-US". By specifically using the "de-DE" culture, the Parse handles the alternative number style.


来源: stackexchange

问:
Why my wordpress website title is not showing when I copy the link to facebook and other social network?
I am building a website like this www.arpandasphotography.com

I have set up the title for the page from the general setting. But when I copy the link to somewhere such as Facebook messenger or whatssap it shows "No Title" as the name. How do I change it?

答:
There is a facebook debugger for situations like this:
https://developers.facebook.com/tools/debug/

It says you're missing og:description.

ContentLicense: CC BY-SA 3.0


问:
How to get field value in the Serializer
I want to get id value passing in the serializer that is

id = serializers.IntegerField(label='ID') in the function to get the profile object

def profile_info(self, obj)

But it giving the error id is IntegerField please pass the int or
  string

Can Anybody tell me how to get values passed in id field thanks.  Down below is my serializer code

```<code>class UserSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(label='ID')
    # print ('dadddaaa ',serializers.data)
    profile = serializers.SerializerMethodField('profile_info')
    username = serializers.CharField()
    first_name = serializers.CharField()
    last_name = serializers.CharField()
    # Nazir = serializers.CharField()
    # profile = UsersSerializer(Profile.objects.get(User.objects.get(pk=serializers.data['id'])))
    def profile_info(self, obj):
        # print ('selffff   ', serializers)
        prof_obj = Profile.objects.get(user=User.objects.get(pk=id))
        return {'id':prof_obj.id}
</code>```

答:
I would not recommend retrieving the related Profile model with a SerializerMethod, because this will fire a separate query for each User. I suggest to use a nested Serializer for the Profile model, so Django/DRF will build a JOIN query. Also, you don't have to specify each field, you can use the fields option of the Meta class.

First, make sure that you specify a related_name for the user-relation in your Profile model, so it will be accessible as a field in the ModelSerializer:

```<code>user = models.OneToOneField(
    settings.AUTH_USER_MODEL,
    on_delete=models.CASCADE,
    related_name='profile',
)
</code>```

Then create a Serializer for each model:

```<code>class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = ('id', 'ship', 'copilot')

class UserSerializer(serializers.ModelSerializer):
    profile = ProfileSerializer(read_only=True)
    class Meta:
        model = User
        fields = ('id', 'profile', 'username', 'first_name', 'last_name')
</code>```

This will give you a JSON like this:

```<code>{
    "id": 1,
    "profile": {
        "id": 1,
        "ship": "Millennium Falcon",
        "copilot": "Chewbacca"
    },
    "username": "hsolo",
    "first_name": "Han",
    "last_name": "Solo"
}
</code>```

Note: By default nested relations are not writable, but it can be done by creating your own create() and update() functions

Body:
I want to get id value passing in the serializer that is

id = serializers.IntegerField(label='ID') in the function to get the profile object

def profile_info(self, obj)

But it giving the error id is IntegerField please pass the int or
  string

Can Anybody tell me how to get values passed in id field thanks.  Down below is my serializer code

class UserSerializer(serializers.ModelSerializer):
    id = serializers.IntegerField(label='ID')
    # print ('dadddaaa ',serializers.data)
    profile = serializers.SerializerMethodField('profile_info')
    username = serializers.CharField()
    first_name = serializers.CharField()
    last_name = serializers.CharField()
    # Nazir = serializers.CharField()
    # profile = UsersSerializer(Profile.objects.get(User.objects.get(pk=serializers.data['id'])))
    def profile_info(self, obj):
        # print ('selffff   ', serializers)
        prof_obj = Profile.objects.get(user=User.objects.get(pk=id))
        return {'id':prof_obj.id}

Body:
I would not recommend retrieving the related Profile model with a SerializerMethod, because this will fire a separate query for each User. I suggest to use a nested Serializer for the Profile model, so Django/DRF will build a JOIN query. Also, you don't have to specify each field, you can use the fields option of the Meta class.

First, make sure that you specify a related_name for the user-relation in your Profile model, so it will be accessible as a field in the ModelSerializer:

user = models.OneToOneField(
    settings.AUTH_USER_MODEL,
    on_delete=models.CASCADE,
    related_name='profile',
)

Then create a Serializer for each model:

class ProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = Profile
        fields = ('id', 'ship', 'copilot')

class UserSerializer(serializers.ModelSerializer):
    profile = ProfileSerializer(read_only=True)
    class Meta:
        model = User
        fields = ('id', 'profile', 'username', 'first_name', 'last_name')

This will give you a JSON like this:

{
    "id": 1,
    "profile": {
        "id": 1,
        "ship": "Millennium Falcon",
        "copilot": "Chewbacca"
    },
    "username": "hsolo",
    "first_name": "Han",
    "last_name": "Solo"
}

Note: By default nested relations are not writable, but it can be done by creating your own create() and update() functions


问:
Dialog on PrimeFaces does not update and calculate date difference
Dialog on PrimeFaces does not update and calculate date difference in my dialog page.

Dialog page:

```<code>        <p:dialog id="GrupoCreateDlg" widgetVar="GrupoCreateDialog" modal="true" resizable="false" appendTo="@(body)" header="#{bundle.CreateGrupoTitle}">
        <h:form id="GrupoCreateForm">
            <h:panelGroup id="display">
                <p:panelGrid columns="2" rendered="#{grupoController.selected != null}">
                    <p:outputLabel value="#{bundle.CreateGrupoLabel_grupo}" for="grupo" />
                    <p:inputText id="grupo" value="#{grupoController.selected.grupo}" title="#{bundle.CreateGrupoTitle_grupo}" required="true" requiredMessage="#{bundle.CreateGrupoRequiredMessage_grupo}"/>
                    <p:outputLabel value="#{bundle.CreateGrupoLabel_usuario}" for="usuario" />
                    <p:inputText id="usuario" value="#{grupoController.selected.usuario}" title="#{bundle.CreateGrupoTitle_usuario}" required="true" requiredMessage="#{bundle.CreateGrupoRequiredMessage_usuario}"/>
                    <p:outputLabel value="#{bundle.CreateGrupoLabel_clave}" for="clave" />
                    <p:inputText id="clave" value="#{grupoController.selected.clave}" title="#{bundle.CreateGrupoTitle_clave}" required="true" requiredMessage="#{bundle.CreateGrupoRequiredMessage_clave}"/>
                    <p:outputLabel value="#{bundle.CreateGrupoLabel_detalle}" for="detalle" />
                    <p:inputText id="detalle" value="#{grupoController.selected.detalle}" title="#{bundle.CreateGrupoTitle_detalle}" />
                    <p:outputLabel value="#{bundle.CreateGrupoLabel_fechainicio}" for="fechainicio" />
                    <p:calendar id="fechainicio" pattern="dd/MM/yyyy" value="#{grupoController.selected.fechainicio}" title="#{bundle.EditGrupoTitle_fechainicio}"
                                locale="es" showOn="button" showButtonPanel="true"/>
                    <p:outputLabel value="#{bundle.CreateGrupoLabel_fechafin}" for="fechafin" />
                    <p:calendar id="fechafin" pattern="dd/MM/yyyy" value="#{grupoController.selected.fechafin}" title="#{bundle.EditGrupoTitle_fechafin}"
                                locale="es" showOn="button" showButtonPanel="true">
                        <p:ajax event="change" update="dias"/>
                    </p:calendar>
                    <p:outputLabel value="Dias"/>
                    <h:outputText id="dias" value="#{grupoController.calcularFechas()}">
                        <f:convertNumber type="number"/>
                    </h:outputText>
                    <p:outputLabel value="#{bundle.CreateGrupoLabel_incidencia}" for="incidencia" />
                    <p:selectBooleanCheckbox id="incidencia" value="#{grupoController.selected.incidencia}" />
                    <p:outputLabel value="#{bundle.CreateGrupoLabel_fechaincidencia}" for="fechaincidencia" />
                    <p:calendar id="fechaincidencia" pattern="dd/MM/yyyy" value="#{grupoController.selected.fechaincidencia}" title="#{bundle.EditGrupoTitle_fechaincidencia}"
                                locale="es" showOn="button" showButtonPanel="true"/>
                    <p:outputLabel value="#{bundle.CreateGrupoLabel_fechaavisocaducidad}" for="fechaavisocaducidad" />
                    <p:calendar id="fechaavisocaducidad" pattern="dd/MM/yyyy HH:mm:ss" value="#{grupoController.selected.fechaavisocaducidad}" title="#{bundle.EditGrupoTitle_fechaavisocaducidad}"
                                locale="es" showOn="button" showButtonPanel="true"/>
                </p:panelGrid>
                <p:commandButton actionListener="#{grupoController.create}" value="#{bundle.Save}" update="display,:GrupoListForm:datalist,:growl" oncomplete="handleSubmit(args,'GrupoCreateDialog');"/>
                <p:commandButton value="#{bundle.Cancel}" onclick="GrupoCreateDialog.hide()"/>
            </h:panelGroup>
        </h:form>
    </p:dialog>
</code>```

Groupo controller:

```<code>    public int calcularFechas() throws ParseException {
    diasDuracion = 0;
    try {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        Date fechaFinal = selected.getFechainicio();
        Date fechaInicial = selected.getFechainicio();

        diasDuracion = (int) ((fechaFinal.getTime() - fechaInicial.getTime()) / 86400000);

        System.out.println("Hay " + diasDuracion + " dias de diferencia");

    } catch (NullPointerException e) {
        e.printStackTrace();
    }
    return diasDuracion;

}
</code>```

The HTML must be show the difference between date initial and finish (on days) in the outputText.
What's wrong?
The outputText dias must be update without close the dialog page.

答:
I copy and paste your stuff into my project and edit it like that:

Put the calcularFechas() into

```<code><p:ajax event="change" update="dias" listener="#{grupoController.calcularFechas()"/>
</code>```

and write a method

getCalcularFechas(){ ...
}

It worked for me like that because the listener was called after the event was fired.

ContentLicense: CC BY-SA 4.0

Body:
Dialog on PrimeFaces does not update and calculate date difference in my dialog page.

Dialog page:

        <h:form id="GrupoCreateForm">
            <h:panelGroup id="display">

                    <h:outputText id="dias" value="#{grupoController.calcularFechas()}">
                        <f:convertNumber type="number"/>
                    </h:outputText>

            </h:panelGroup>
        </h:form>

Groupo controller:

    public int calcularFechas() throws ParseException {
    diasDuracion = 0;
    try {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        Date fechaFinal = selected.getFechainicio();
        Date fechaInicial = selected.getFechainicio();

        diasDuracion = (int) ((fechaFinal.getTime() - fechaInicial.getTime()) / 86400000);

        System.out.println("Hay " + diasDuracion + " dias de diferencia");

    } catch (NullPointerException e) {
        e.printStackTrace();
    }
    return diasDuracion;

}

The HTML must be show the difference between date initial and finish (on days) in the outputText.
What's wrong?
The outputText dias must be update without close the dialog page.

Body:
I copy and paste your stuff into my project and edit it like that:

Put the calcularFechas() into

<p:ajax event="change" update="dias" listener="#{grupoController.calcularFechas()"/>

and write a method

getCalcularFechas(){ ...
}

It worked for me like that because the listener was called after the event was fired.


问:
After installing with pip, "jupyter: command not found"
After installing with pip install jupyter, terminal still cannot find jupyter notebook.

Ubuntu simply says command not found.  Similar with ipython.  Did pip not get install properly or something?  How does Ubuntu know where to look for executables installed with pip?

答:
I tried both,

```<code>pip install jupyter
</code>```

and

```<code>pip3 install jupyter
</code>```

but finally got it done using

```<code>sudo -H pip install jupyter
</code>```

execute a command as another user -H

The -H (HOME) option requests that the security policy set the HOME environment variable to the home directory of the target user (root by default) as specified by the password database. Depending on the policy, this may be the default behavior.

Body:
I tried both,

pip install jupyter

and

pip3 install jupyter

but finally got it done using

sudo -H pip install jupyter

execute a command as another user -H

The -H (HOME) option requests that the security policy set the HOME environment variable to the home directory of the target user (root by default) as specified by the password database. Depending on the policy, this may be the default behavior.


问:
SQL select users that belong to the same object
I have a MySQL database set up where I have a User, Project, and ProjectUser table. The ProjectUser table has a UserID and ProjectID and maps a user to a project. I want to be able to query which projects two different users have in common. So if Bob belongs to projects A, B, C, D and Joe belongs to projects C, D, E, F... then I want to SELECT the information for projects C and D when I know the UserID of Bob and Joe.</p>

答:
Assume this is the metadata and the examples you provided.

```<code>create table User        (UserID    int, Name varchar(200));
create table Project     (ProjectID int, Name varchar(200), Information varchar(200));
create table ProjectUser (UserID    int, ProjectID int    );

INSERT INTO User        VALUE (1,'Bob'),(2,'Joe');
INSERT INTO Project     VALUE (1,'A','First'),(2,'B','Second'),(3,'C','Third'),(4,'D','Fourth'),(5,'E','Fifth'),(6,'F','Sixth');
INSERT INTO ProjectUser VALUE (1,1),(1,2),(1,3),(1,4),(2,3),(2,4),(2,5),(2,6);
</code>```

Assuming the records in ProjectUser table are unique by UserID and ProjectID, you can get the details of projects Bob and Joe share by:

```<code>SELECT Project.* FROM Project WHERE Project.ProjectID IN
(
   SELECT Project.ProjectID

   FROM ProjectUser

   INNER JOIN User
   ON User.UserID       = ProjectUser.UserID

   INNER JOIN Project
   ON Project.ProjectID = ProjectUser.ProjectID

   WHERE User.Name IN ('Bob','Joe')

   GROUP BY Project.ProjectID

   HAVING COUNT(*) > 1
)
</code>```

Try it on http://sqlfiddle.com/

Body:
Assume this is the metadata and the examples you provided.

create table User        (UserID    int, Name varchar(200));
create table Project     (ProjectID int, Name varchar(200), Information varchar(200));
create table ProjectUser (UserID    int, ProjectID int    );

INSERT INTO User        VALUE (1,'Bob'),(2,'Joe');
INSERT INTO Project     VALUE (1,'A','First'),(2,'B','Second'),(3,'C','Third'),(4,'D','Fourth'),(5,'E','Fifth'),(6,'F','Sixth');
INSERT INTO ProjectUser VALUE (1,1),(1,2),(1,3),(1,4),(2,3),(2,4),(2,5),(2,6);

Assuming the records in ProjectUser table are unique by UserID and ProjectID, you can get the details of projects Bob and Joe share by:

SELECT Project.* FROM Project WHERE Project.ProjectID IN
(
   SELECT Project.ProjectID

   FROM ProjectUser

   INNER JOIN User
   ON User.UserID       = ProjectUser.UserID

   INNER JOIN Project
   ON Project.ProjectID = ProjectUser.ProjectID

   WHERE User.Name IN ('Bob','Joe')

   GROUP BY Project.ProjectID

   HAVING COUNT(*) > 1
)

Try it on http://sqlfiddle.com/


问:
jquery return value of input to var
I'm trying to make a variable equal the value of the text box. I have the text box value being set to a variable and returned as an alert (for now) but I can't figure out how to call that variable from other functions.

```<code>$('#max_char').keyup(function () {
    var max_char = $(this).val();
    alert(max_char + ' Handler for .keyup() called.');
});

var count_options = {
    'maxCharacterSize': max_char,
    'originalStyle': 'originalDisplayInfo',
    'warningStyle': 'warningDisplayInfo',
    'warningNumber': 40,
    'displayFormat': '#input Characters | #left Characters Left | #words Words'
};

$('#textinput').textareaCount(count_options);
});
</code>```

HTML

```<code><textarea cols="68" rows="21" name="textinput" id="textinput"></textarea><br/>
    <input type="textbox" id="max_char" name="max_char" value="-1" /> Max Characters <br/>
</code>```

Any help would be great. Trying to add the var max_char to the maxCharacterSize of count_options

答:
If I understand you correctly, if you declare the var within the global scope of javascript

Or if you directly access the input with

```<code>$("#max_char").val()
</code>```

ContentLicense: CC BY-SA 2.5

Title: jquery return value of input to var

Body:
I'm trying to make a variable equal the value of the text box. I have the text box value being set to a variable and returned as an alert (for now) but I can't figure out how to call that variable from other functions.

$('#max_char').keyup(function () {
    var max_char = $(this).val();
    alert(max_char + ' Handler for .keyup() called.');
});

var count_options = {
    'maxCharacterSize': max_char,
    'originalStyle': 'originalDisplayInfo',
    'warningStyle': 'warningDisplayInfo',
    'warningNumber': 40,
    'displayFormat': '#input Characters | #left Characters Left | #words Words'
};

$('#textinput').textareaCount(count_options);
});

HTML

<textarea cols="68" rows="21" name="textinput" id="textinput"></textarea>

    <input type="textbox" id="max_char" name="max_char" value="-1" /> Max Characters

Any help would be great. Trying to add the var max_char to the maxCharacterSize of count_options

Body:
If I understand you correctly, if you declare the var within the global scope of javascript

Or if you directly access the input with

$("#max_char").val()


问:
Calling Async Methods in Action Filters in MVC 5
I'm writing an Action Filter (inheriting from ActionFilterAttribute) which uses HttpClient to POST data to an external server in the OnResultExecuted method. HttpClient has the method PostAsync which returns an awaitable Task<HttpResponseMessage>.

```<code>public override void OnResultExecuted(ResultExecutedContext filterContext)
{
    using (var client = new HttpClient())
    {
        var task = client.PostAsync(GetUri(), GetContent());
        var result = task.Result; // blocking
    }
}
</code>```

The accepted answer to Async action filter in MVC 4 says it is not possible in MVC 4.

Is this still true in MVC 5, and if so what is the best way of calling this asynchronous method without blocking the thread?

答:
Some guy kind of 'back ported' it here

https://github.com/jdaigle/Hydrogen.Extensions.Mvc5

I haven't tried it and can't recommend it but if you're in transition to .NET Core it might be worth considering. Fortunately I managed to remove all async code from my extension - this time.

Body:
I'm writing an Action Filter (inheriting from ActionFilterAttribute) which uses HttpClient to POST data to an external server in the OnResultExecuted method. HttpClient has the method PostAsync which returns an awaitable Task<HttpResponseMessage>.

public override void OnResultExecuted(ResultExecutedContext filterContext)
{
    using (var client = new HttpClient())
    {
        var task = client.PostAsync(GetUri(), GetContent());
        var result = task.Result; // blocking
    }
}

The accepted answer to Async action filter in MVC 4 says it is not possible in MVC 4.

Is this still true in MVC 5, and if so what is the best way of calling this asynchronous method without blocking the thread?


问:
Getting an Extra Empty line when exporting Excel Range to .txt file
I am trying to copy an Excel range to a .txt file.

The export is successful, with one exception, It adds one "extra" empty line at the end.

I've read and tests many of the solution on SO (and other sites), but still without any success.

My Code (relevant part)

```<code>' === Export to the .txt file ===
Dim TxtFileName As String, lineText As String

TxtFileName = ThisWorkbook.Path & "\Inv_" & Format(Date, "yyyymmdd") & ".txt"

Open TxtFileName For Output As #1
With StockSht
    For i = 1 To LastRow
        For j = 1 To 3
            If j = 3 Then
                lineText = lineText & .Cells(i, j).Value2
            Else ' j = 1 or 2
                lineText = lineText & .Cells(i, j).Value2 & vbTab
            End If
        Next j
        Print #1, lineText
        lineText = ""
    Next i
End With
Close #1
</code>```

My StockSht (worksheet object) and LastRow are defined correctly, and getting their values.

Screen-shot of the end of the exported .txt file

答:
You can use a semi-colon in the Print statement to control the insertion point (i.e. prevent the line-feed on the last line).

The relevant bit on the MSDN page:

Use a semicolon to position the insertion point immediately after the last character displayed.

I tested this code:

```<code>Sub PrintTest()

    Dim lng As Long

    Open "C:\foo3.txt" For Output As #1

    For lng = 1 To 10
        If lng < 10 Then
            Print #1, "foo" & lng
        Else
            Print #1, "foo" & lng; '<-- semi-colon prevents the newline
        End If
    Next lng

    Close #1

End Sub
</code>```

So I would update your code like below (not tested):

```<code>' === Export to the .txt file ===
Dim TxtFileName As String, lineText As String

TxtFileName = ThisWorkbook.Path & "\Inv_" & Format(Date, "yyyymmdd") & ".txt"

Open TxtFileName For Output As #1
With StockSht
    For i = 1 To LastRow
        For j = 1 To 3
            If j = 3 Then
                lineText = lineText & .Cells(i, j).Value2
            Else ' j = 1 or 2
                lineText = lineText & .Cells(i, j).Value2 & vbTab
            End If
        Next j

        '--- new bit: check for i against LastRow and add the semicolon on last row
        If i <> LastRow Then
            Print #1, lineText
        Else
            Print #1, lineText; '<-- semi colon keeps insertion point at end of line
        End If

        lineText = ""
    Next i
End With
Close #1
</code>```

Body:
I am trying to copy an Excel range to a .txt file.

The export is successful, with one exception, It adds one "extra" empty line at the end.

I've read and tests many of the solution on SO (and other sites), but still without any success.

My Code (relevant part)

' === Export to the .txt file ===
Dim TxtFileName As String, lineText As String

TxtFileName = ThisWorkbook.Path & "\Inv_" & Format(Date, "yyyymmdd") & ".txt"

Open TxtFileName For Output As #1
With StockSht
    For i = 1 To LastRow
        For j = 1 To 3
            If j = 3 Then
                lineText = lineText & .Cells(i, j).Value2
            Else ' j = 1 or 2
                lineText = lineText & .Cells(i, j).Value2 & vbTab
            End If
        Next j
        Print #1, lineText
        lineText = ""
    Next i
End With
Close #1

My StockSht (worksheet object) and LastRow are defined correctly, and getting their values.

Screen-shot of the end of the exported .txt file

Body:
You can use a semi-colon in the Print statement to control the insertion point (i.e. prevent the line-feed on the last line).

The relevant bit on the MSDN page:

Use a semicolon to position the insertion point immediately after the last character displayed.

I tested this code:

Sub PrintTest()

    Dim lng As Long

    Open "C:\foo3.txt" For Output As #1

    For lng = 1 To 10
        If lng < 10 Then
            Print #1, "foo" & lng
        Else
            Print #1, "foo" & lng; '<-- semi-colon prevents the newline
        End If
    Next lng

    Close #1

End Sub

So I would update your code like below (not tested):

' === Export to the .txt file ===
Dim TxtFileName As String, lineText As String

TxtFileName = ThisWorkbook.Path & "\Inv_" & Format(Date, "yyyymmdd") & ".txt"

Open TxtFileName For Output As #1
With StockSht
    For i = 1 To LastRow
        For j = 1 To 3
            If j = 3 Then
                lineText = lineText & .Cells(i, j).Value2
            Else ' j = 1 or 2
                lineText = lineText & .Cells(i, j).Value2 & vbTab
            End If
        Next j

        '--- new bit: check for i against LastRow and add the semicolon on last row
        If i <> LastRow Then
            Print #1, lineText
        Else
            Print #1, lineText; '<-- semi colon keeps insertion point at end of line
        End If

        lineText = ""
    Next i
End With
Close #1


问:
Google Play Store - Disable debug mode
Can you please help me?

I try upload my application for google play store, and this problem:
"You uploaded a debuggable APK. For security reasons you need to disable debugging before it can be published in Google Play

What this need setting? Thank you very mutch!

答: Don't use the debug variant output! Build a release apk. You can do that in Android Studio by going to the menu Build -> Generate Signed APK. </p>

Title: Google Play Store - Disable debug mode


问:
Adwords API Modify class in order to pass a variable and get response in variable
I'm trying to modify a class given from a PHP script example from the Adwords API.

I'm pretty new to playing with Objects in PHP so I can't figure out how to make it work.

I would like to modify this script below in order to pass on a keyword array as a variable, therefore replacing the keywords contained in:

```<code>$relatedToQuerySearchParameter->setQueries([
        'bakery', 'pastries', 'birthday cake'
    ]);
</code>```

Maybe to use it as a function will normally do :

```<code>function GetKeywordIdeas($array_keywords){...}
</code>```

And then get the results in a variable

Here's the code from the example:

```<code><?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Google\AdsApi\Examples\AdWords\v201710\Optimization;

require __DIR__ . '/../../../../vendor/autoload.php';

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201710\cm\Language;
use Google\AdsApi\AdWords\v201710\cm\NetworkSetting;
use Google\AdsApi\AdWords\v201710\cm\Paging;
use Google\AdsApi\AdWords\v201710\o\AttributeType;
use Google\AdsApi\AdWords\v201710\o\IdeaType;
use Google\AdsApi\AdWords\v201710\o\LanguageSearchParameter;
use Google\AdsApi\AdWords\v201710\o\NetworkSearchParameter;
use Google\AdsApi\AdWords\v201710\o\RelatedToQuerySearchParameter;
use Google\AdsApi\AdWords\v201710\o\RequestType;
use Google\AdsApi\AdWords\v201710\o\SeedAdGroupIdSearchParameter;
use Google\AdsApi\AdWords\v201710\o\TargetingIdeaSelector;
use Google\AdsApi\AdWords\v201710\o\TargetingIdeaService;
use Google\AdsApi\Common\OAuth2TokenBuilder;
use Google\AdsApi\Common\Util\MapEntries;

/**
 * This example gets keyword ideas related to a seed keyword.
 */
class GetKeywordIdeas {

  // If you do not want to use an existing ad group to seed your request, you
  // can set this to null.
  const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';
  const PAGE_LIMIT = 500;

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session, $adGroupId) {
    $targetingIdeaService =
        $adWordsServices->get($session, TargetingIdeaService::class);

    // Create selector.
    $selector = new TargetingIdeaSelector();
    $selector->setRequestType(RequestType::IDEAS);
    $selector->setIdeaType(IdeaType::KEYWORD);
    $selector->setRequestedAttributeTypes([
        AttributeType::KEYWORD_TEXT,
        AttributeType::SEARCH_VOLUME,
        AttributeType::AVERAGE_CPC,
        AttributeType::COMPETITION,
        AttributeType::CATEGORY_PRODUCTS_AND_SERVICES
    ]);

    $paging = new Paging();
    $paging->setStartIndex(0);
    $paging->setNumberResults(10);
    $selector->setPaging($paging);

    $searchParameters = [];
    // Create related to query search parameter.
    $relatedToQuerySearchParameter = new RelatedToQuerySearchParameter();
    $relatedToQuerySearchParameter->setQueries([
        'bakery', 'pastries', 'birthday cake'
    ]);
    $searchParameters[] = $relatedToQuerySearchParameter;

    // Create language search parameter (optional).
    // The ID can be found in the documentation:
    // https://developers.google.com/adwords/api/docs/appendix/languagecodes
    $languageParameter = new LanguageSearchParameter();
    $english = new Language();
    $english->setId(1000);
    $languageParameter->setLanguages([$english]);
    $searchParameters[] = $languageParameter;

    // Create network search parameter (optional).
    $networkSetting = new NetworkSetting();
    $networkSetting->setTargetGoogleSearch(true);
    $networkSetting->setTargetSearchNetwork(false);
    $networkSetting->setTargetContentNetwork(false);
    $networkSetting->setTargetPartnerSearchNetwork(false);

    $networkSearchParameter = new NetworkSearchParameter();
    $networkSearchParameter->setNetworkSetting($networkSetting);
    $searchParameters[] = $networkSearchParameter;

    // Optional: Use an existing ad group to generate ideas.
    if (!empty($adGroupId)) {
      $seedAdGroupIdSearchParameter = new SeedAdGroupIdSearchParameter();
      $seedAdGroupIdSearchParameter->setAdGroupId($adGroupId);
      $searchParameters[] = $seedAdGroupIdSearchParameter;
    }
    $selector->setSearchParameters($searchParameters);
    $selector->setPaging(new Paging(0, self::PAGE_LIMIT));

    // Get keyword ideas.
    $page = $targetingIdeaService->get($selector);

    // Print out some information for each targeting idea.
    $entries = $page->getEntries();
    if ($entries !== null) {
      foreach ($entries as $targetingIdea) {
        $data = MapEntries::toAssociativeArray($targetingIdea->getData());
        $keyword = $data[AttributeType::KEYWORD_TEXT]->getValue();
        $searchVolume =
            ($data[AttributeType::SEARCH_VOLUME]->getValue() !== null)
            ? $data[AttributeType::SEARCH_VOLUME]->getValue() : 0;
        $averageCpc = $data[AttributeType::AVERAGE_CPC]->getValue();
        $competition = $data[AttributeType::COMPETITION]->getValue();
        $categoryIds =
            ($data[AttributeType::CATEGORY_PRODUCTS_AND_SERVICES]->getValue()
                === null)
            ? $categoryIds = '' : implode(
                ', ',
                $data[AttributeType::CATEGORY_PRODUCTS_AND_SERVICES]->getValue()
            );
        printf(
            "Keyword with text '%s', average monthly search volume %d, "
                . "average CPC %d, and competition %.2f "
                . "was found with categories: %s\n",
            $keyword,
            $searchVolume,
            ($averageCpc === null) ? 0 : $averageCpc->getMicroAmount(),
            $competition,
            $categoryIds
        );
      }
    }

    if (empty($entries)) {
      print "No related keywords were found.\n";
    }
  }

  public static function main() {
    // Generate a refreshable OAuth2 credential for authentication.
    $oAuth2Credential = (new OAuth2TokenBuilder())
        ->fromFile()
        ->build();

    // Construct an API session configured from a properties file and the OAuth2
    // credentials above.
    $session = (new AdWordsSessionBuilder())
        ->fromFile()
        ->withOAuth2Credential($oAuth2Credential)
        ->build();
    self::runExample(new AdWordsServices(), $session, self::AD_GROUP_ID);
  }
}

GetKeywordIdeas::main();
</code>```

Thanks for your help or explanations.

答:
you need to change 4 lines in the code. 1.

```<code>  public static function main() {
</code>```

to

```<code>public static function main($array_keywords) {
</code>```

and 2.

```<code>self::runExample(new AdWordsServices(), $session, self::AD_GROUP_ID);
</code>```

to

```<code>self::runExample(new AdWordsServices(), $session, self::AD_GROUP_ID, $array_keywords);
</code>```

and 3.

```<code> public static function runExample(AdWordsServices $adWordsServices,
  AdWordsSession $session, $adGroupId) {
</code>```

to

```<code> public static function runExample(AdWordsServices $adWordsServices,
  AdWordsSession $session, $adGroupId, $array_keywords) {
</code>```

and 4.

```<code>    $relatedToQuerySearchParameter->setQueries([
    'bakery', 'pastries', 'birthday cake'
]);
</code>```

to

```<code>    $relatedToQuerySearchParameter->setQueries($array_keywords);
</code>```

then you can call it like this:

```<code>GetKeywordIdeas::main($array_keywords);
</code>```

Body:
I'm trying to modify a class given from a PHP script example from the Adwords API.

I'm pretty new to playing with Objects in PHP so I can't figure out how to make it work.

I would like to modify this script below in order to pass on a keyword array as a variable, therefore replacing the keywords contained in:

$relatedToQuerySearchParameter->setQueries([
        'bakery', 'pastries', 'birthday cake'
    ]);

Maybe to use it as a function will normally do :

function GetKeywordIdeas($array_keywords){...}

And then get the results in a variable

Here's the code from the example:

<?php
/**
 * Copyright 2017 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
namespace Google\AdsApi\Examples\AdWords\v201710\Optimization;

require __DIR__ . '/../../../../vendor/autoload.php';

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSession;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201710\cm\Language;
use Google\AdsApi\AdWords\v201710\cm\NetworkSetting;
use Google\AdsApi\AdWords\v201710\cm\Paging;
use Google\AdsApi\AdWords\v201710\o\AttributeType;
use Google\AdsApi\AdWords\v201710\o\IdeaType;
use Google\AdsApi\AdWords\v201710\o\LanguageSearchParameter;
use Google\AdsApi\AdWords\v201710\o\NetworkSearchParameter;
use Google\AdsApi\AdWords\v201710\o\RelatedToQuerySearchParameter;
use Google\AdsApi\AdWords\v201710\o\RequestType;
use Google\AdsApi\AdWords\v201710\o\SeedAdGroupIdSearchParameter;
use Google\AdsApi\AdWords\v201710\o\TargetingIdeaSelector;
use Google\AdsApi\AdWords\v201710\o\TargetingIdeaService;
use Google\AdsApi\Common\OAuth2TokenBuilder;
use Google\AdsApi\Common\Util\MapEntries;

/**
 * This example gets keyword ideas related to a seed keyword.
 */
class GetKeywordIdeas {

  // If you do not want to use an existing ad group to seed your request, you
  // can set this to null.
  const AD_GROUP_ID = 'INSERT_AD_GROUP_ID_HERE';
  const PAGE_LIMIT = 500;

  public static function runExample(AdWordsServices $adWordsServices,
      AdWordsSession $session, $adGroupId) {
    $targetingIdeaService =
        $adWordsServices->get($session, TargetingIdeaService::class);

    // Create selector.
    $selector = new TargetingIdeaSelector();
    $selector->setRequestType(RequestType::IDEAS);
    $selector->setIdeaType(IdeaType::KEYWORD);
    $selector->setRequestedAttributeTypes([
        AttributeType::KEYWORD_TEXT,
        AttributeType::SEARCH_VOLUME,
        AttributeType::AVERAGE_CPC,
        AttributeType::COMPETITION,
        AttributeType::CATEGORY_PRODUCTS_AND_SERVICES
    ]);

    $paging = new Paging();
    $paging->setStartIndex(0);
    $paging->setNumberResults(10);
    $selector->setPaging($paging);

    $searchParameters = [];
    // Create related to query search parameter.
    $relatedToQuerySearchParameter = new RelatedToQuerySearchParameter();
    $relatedToQuerySearchParameter->setQueries([
        'bakery', 'pastries', 'birthday cake'
    ]);
    $searchParameters[] = $relatedToQuerySearchParameter;

    // Create language search parameter (optional).
    // The ID can be found in the documentation:
    // https://developers.google.com/adwords/api/docs/appendix/languagecodes
    $languageParameter = new LanguageSearchParameter();
    $english = new Language();
    $english->setId(1000);
    $languageParameter->setLanguages([$english]);
    $searchParameters[] = $languageParameter;

    // Create network search parameter (optional).
    $networkSetting = new NetworkSetting();
    $networkSetting->setTargetGoogleSearch(true);
    $networkSetting->setTargetSearchNetwork(false);
    $networkSetting->setTargetContentNetwork(false);
    $networkSetting->setTargetPartnerSearchNetwork(false);

    $networkSearchParameter = new NetworkSearchParameter();
    $networkSearchParameter->setNetworkSetting($networkSetting);
    $searchParameters[] = $networkSearchParameter;

    // Optional: Use an existing ad group to generate ideas.
    if (!empty($adGroupId)) {
      $seedAdGroupIdSearchParameter = new SeedAdGroupIdSearchParameter();
      $seedAdGroupIdSearchParameter->setAdGroupId($adGroupId);
      $searchParameters[] = $seedAdGroupIdSearchParameter;
    }
    $selector->setSearchParameters($searchParameters);
    $selector->setPaging(new Paging(0, self::PAGE_LIMIT));

    // Get keyword ideas.
    $page = $targetingIdeaService->get($selector);

    // Print out some information for each targeting idea.
    $entries = $page->getEntries();
    if ($entries !== null) {
      foreach ($entries as $targetingIdea) {
        $data = MapEntries::toAssociativeArray($targetingIdea->getData());
        $keyword = $data[AttributeType::KEYWORD_TEXT]->getValue();
        $searchVolume =
            ($data[AttributeType::SEARCH_VOLUME]->getValue() !== null)
            ? $data[AttributeType::SEARCH_VOLUME]->getValue() : 0;
        $averageCpc = $data[AttributeType::AVERAGE_CPC]->getValue();
        $competition = $data[AttributeType::COMPETITION]->getValue();
        $categoryIds =
            ($data[AttributeType::CATEGORY_PRODUCTS_AND_SERVICES]->getValue()
                === null)
            ? $categoryIds = '' : implode(
                ', ',
                $data[AttributeType::CATEGORY_PRODUCTS_AND_SERVICES]->getValue()
            );
        printf(
            "Keyword with text '%s', average monthly search volume %d, "
                . "average CPC %d, and competition %.2f "
                . "was found with categories: %s\n",
            $keyword,
            $searchVolume,
            ($averageCpc === null) ? 0 : $averageCpc->getMicroAmount(),
            $competition,
            $categoryIds
        );
      }
    }

    if (empty($entries)) {
      print "No related keywords were found.\n";
    }
  }

  public static function main() {
    // Generate a refreshable OAuth2 credential for authentication.
    $oAuth2Credential = (new OAuth2TokenBuilder())
        ->fromFile()
        ->build();

    // Construct an API session configured from a properties file and the OAuth2
    // credentials above.
    $session = (new AdWordsSessionBuilder())
        ->fromFile()
        ->withOAuth2Credential($oAuth2Credential)
        ->build();
    self::runExample(new AdWordsServices(), $session, self::AD_GROUP_ID);
  }
}

GetKeywordIdeas::main();

Thanks for your help or explanations.

Body:
you need to change 4 lines in the code. 1.

  public static function main() {

to

public static function main($array_keywords) {

and 2.

self::runExample(new AdWordsServices(), $session, self::AD_GROUP_ID);

to

self::runExample(new AdWordsServices(), $session, self::AD_GROUP_ID, $array_keywords);

and 3.

 public static function runExample(AdWordsServices $adWordsServices,
  AdWordsSession $session, $adGroupId) {

to

 public static function runExample(AdWordsServices $adWordsServices,
  AdWordsSession $session, $adGroupId, $array_keywords) {

and 4.

    $relatedToQuerySearchParameter->setQueries([
    'bakery', 'pastries', 'birthday cake'
]);

to

    $relatedToQuerySearchParameter->setQueries($array_keywords);

then you can call it like this:

GetKeywordIdeas::main($array_keywords);


问:
Linux-Live-system inc. Ruby 1.9 on USB-Stick with r/w-Partition
well guess that many of you have great expertise on Linux. I currently have some issues with creating a linux-live-medium.

i have a box with OpenSuse-Linux Version 11.3 with all nice things. Several languages run very well: Perl, Python, PHP! All is very well! BTW - i am very glad that Perl runs very nice.

But I am not able to install Ruby 1.9. Everytime i want to do that i end up with Ruby 1.8.7. I want to testrun some ruby-code. Therefore i need Ruby with the following gems

mechanize
nokogiri
utf8_utils

I heard of a Linux-Live-medium that is able to run with all the wanted things including Ruby 1.9.
Therefore the Live-medium is installed on a USB-Stick with R/W partitions. Is this possible.

I am not a linux-expert - but with all the expertise here i think it is possible to create such a USB-Stick. (...with Ruby 1.9 and all with all that extensions)
I love to hear from you!

best regards
zero

答:
This will actually be a better solution for you- use RVM:

https://rvm.io/

Then you can easily switch back and forth from 1.8 to 1.9 as desired and make 1.9.2 your default.  Just read their docs carefully, it really makes gem management a lot easier.


问:
How to reverse arrows (tails) in Diagrammer, R?
Let's create a very simple diagram:

```<code>niv <- c("A","B","C","D","E")
from <- c("A","A","A","E","B","C","D")
to <-   c("B","C","D","B","C","A","E")
arr <- c(rep("normal",6), "inv")
temp <- data.table(from=factor(from, levels=niv),
to=factor(to,levels=niv))
nodes <- create_node_df(n=length(niv), label=niv,
width=0.3)
edges <- create_edge_df(from = temp$from,
to = temp$to, rel = "leading_to", label=temp$from,
arrowhead=arr, penwidth=3, color="blue")
graph <- create_graph(nodes_df=nodes,edges_df=edges)
render_graph(graph)
</code>```

The diagram shows edges from one node to another.

Usually people paint that edges with an arrow head, but I would like to paint some with the opposite symbol, a tail head.

I've found that by using the parameter arrowhead="inv" I can change the arrow to be a tail instead. (In my example the edge from D to E has a tail).

But there is a problem, the tail is painted on the wrong side.  I would like to paint it at the beginning of the edge (arrow).

How can I change it?

There is a parameter rel = "leading_to"  but I haven't been able to find what other values it can get.

Also there is a parameter "dir" but I don't know how to use it either.

Thanks.

A bonus question would be: How to prevent Diagrammer from writing the labels just above the edges?  I would like they don't overlap.

答:
You can switch the dir to "back":</p>

```<code>library(DiagrammeR)
library(data.table)
niv <- c("A","B","C","D","E")
from <- c("A","A","A","E","B","C","D")
to <-   c("B","C","D","B","C","A","E")
temp <- data.table(from=factor(from, levels=niv),
                   to=factor(to,levels=niv))
nodes <- create_node_df(n=length(niv), label=niv,
                        width=0.3)
edges <- create_edge_df(from = temp$from,
                        to = temp$to, dir = "back", label=temp$from,
                        arrowtail="inv", penwidth=3, color="blue")
graph <- create_graph(nodes_df=nodes,edges_df=edges)
render_graph(graph)
</code>```

Body:
Let's create a very simple diagram:

niv <- c("A","B","C","D","E")
from <- c("A","A","A","E","B","C","D")
to <-   c("B","C","D","B","C","A","E")
arr <- c(rep("normal",6), "inv")
temp <- data.table(from=factor(from, levels=niv),
to=factor(to,levels=niv))
nodes <- create_node_df(n=length(niv), label=niv,
width=0.3)
edges <- create_edge_df(from = temp$from,
to = temp$to, rel = "leading_to", label=temp$from,
arrowhead=arr, penwidth=3, color="blue")
graph <- create_graph(nodes_df=nodes,edges_df=edges)
render_graph(graph)

The diagram shows edges from one node to another.

Usually people paint that edges with an arrow head, but I would like to paint some with the opposite symbol, a tail head.

I've found that by using the parameter arrowhead="inv" I can change the arrow to be a tail instead. (In my example the edge from D to E has a tail).

But there is a problem, the tail is painted on the wrong side.  I would like to paint it at the beginning of the edge (arrow).

How can I change it?

There is a parameter rel = "leading_to"  but I haven't been able to find what other values it can get.

Also there is a parameter "dir" but I don't know how to use it either.

Thanks.

A bonus question would be: How to prevent Diagrammer from writing the labels just above the edges?  I would like they don't overlap.

Body:
You can switch the dir to "back":

library(DiagrammeR)
library(data.table)
niv <- c("A","B","C","D","E")
from <- c("A","A","A","E","B","C","D")
to <-   c("B","C","D","B","C","A","E")
temp <- data.table(from=factor(from, levels=niv),
                   to=factor(to,levels=niv))
nodes <- create_node_df(n=length(niv), label=niv,
                        width=0.3)
edges <- create_edge_df(from = temp$from,
                        to = temp$to, dir = "back", label=temp$from,
                        arrowtail="inv", penwidth=3, color="blue")
graph <- create_graph(nodes_df=nodes,edges_df=edges)
render_graph(graph)


问:
Swift Firebase QueryLimitedToFirst
Hi I am trying to limit a feed to the most recent two posts from users. I was reading the Firebase documentation and it said simply to add "queryLimited(toFirst: Int)" and so far it has not been working, my feed still retrieves all the posts from each user. At the very top is where I have implemented the "queryLimited".

Edit

The way my code is right now, it is only limiting the users and not the posts(json tree below) so how can I change it to limit the posts of each user?

```<code>func getAllPosts(refreshing: Bool, refreshControl: UIRefreshControl?) {
    let ref = Database.database().reference().child("posts").queryLimited(toFirst: 2)
    MBProgressHUD.showAdded(to: self.view, animated: true)
    ref.queryOrdered(byChild: "businessName").observe(.childAdded, with: { snapshot in
        //observeSingleEvent(of: .value, with: { snapshot in
        if let dict = snapshot.value as? NSDictionary {
            self.feeds = []
            for item in dict {
                let json = JSON(item.value)
                let uid = json["uid"].stringValue
                var name: String = json["businessName"].stringValue
                let address: String = json["businessStreet"].stringValue
                let state: String = json["businessCity"].stringValue
                let caption: String = json["caption"].stringValue
                let downloadURL: String = json["download_url"].stringValue
                let timestamp = json["timestamp"].doubleValue
                let date = Date(timeIntervalSince1970: timestamp/1000)
                let postID: String = json["postID"].stringValue

                let lat = json["businessLatitude"].doubleValue
                let long = json["businessLongitude"].doubleValue
                let businessLocation = CLLocation(latitude: lat, longitude: long)

                let latitude = self.locationManager.location?.coordinate.latitude
                let longitude = self.locationManager.location?.coordinate.longitude
                let userLocation = CLLocation(latitude: latitude!, longitude: longitude!)

                let distanceInMeters: Double = userLocation.distance(from: businessLocation)
                let distanceInMiles: Double = distanceInMeters * 0.00062137
                let distanceLabelText = String(format: "%.2f miles away", distanceInMiles)

                self.uid = json["uid"].stringValue

                let usersReference = Database.database().reference(withPath: "users").queryOrderedByKey().queryEqual(toValue: uid)
                usersReference.observeSingleEvent(of: .value, with: { snapshot in
                    if let dict = snapshot.value as? NSDictionary {
                        let userInfo = dict.allValues[0]
                        let userJSON = JSON(userInfo)
                        name = userJSON["name"].stringValue

                    }
                    let post = Post(uid: uid, caption: caption, downloadURL: downloadURL, name: name, date: date, address: address, state: state, distance: distanceLabelText, postID: postID)

                    self.feeds.append(post)

                    // sort posts by date/distance
                    self.feeds.sort {$0.date.compare($1.date) == .orderedDescending}
                    self.feeds.sort {$0.distance.compare($1.distance) == .orderedAscending}
                    self.feedTableView.reloadData()

                })
            }
        }
        if refreshing {
            refreshControl?.endRefreshing()
        }
        MBProgressHUD.hide(for: self.view, animated: true)
    })
}
</code>```

答:
I'm pretty sure that the order query must precede the limit query.</p>

```<code>let ref = Database.database().reference().child("posts").queryOrdered(byChild: "businessName").queryLimited(toFirst: 2)
</code>```

Title: Swift Firebase QueryLimitedToFirst

Body:
Hi I am trying to limit a feed to the most recent two posts from users. I was reading the Firebase documentation and it said simply to add "queryLimited(toFirst: Int)" and so far it has not been working, my feed still retrieves all the posts from each user. At the very top is where I have implemented the "queryLimited".

Edit

The way my code is right now, it is only limiting the users and not the posts(json tree below) so how can I change it to limit the posts of each user?

func getAllPosts(refreshing: Bool, refreshControl: UIRefreshControl?) {
    let ref = Database.database().reference().child("posts").queryLimited(toFirst: 2)
    MBProgressHUD.showAdded(to: self.view, animated: true)
    ref.queryOrdered(byChild: "businessName").observe(.childAdded, with: { snapshot in
        //observeSingleEvent(of: .value, with: { snapshot in
        if let dict = snapshot.value as? NSDictionary {
            self.feeds = []
            for item in dict {
                let json = JSON(item.value)
                let uid = json["uid"].stringValue
                var name: String = json["businessName"].stringValue
                let address: String = json["businessStreet"].stringValue
                let state: String = json["businessCity"].stringValue
                let caption: String = json["caption"].stringValue
                let downloadURL: String = json["download_url"].stringValue
                let timestamp = json["timestamp"].doubleValue
                let date = Date(timeIntervalSince1970: timestamp/1000)
                let postID: String = json["postID"].stringValue

                let lat = json["businessLatitude"].doubleValue
                let long = json["businessLongitude"].doubleValue
                let businessLocation = CLLocation(latitude: lat, longitude: long)

                let latitude = self.locationManager.location?.coordinate.latitude
                let longitude = self.locationManager.location?.coordinate.longitude
                let userLocation = CLLocation(latitude: latitude!, longitude: longitude!)

                let distanceInMeters: Double = userLocation.distance(from: businessLocation)
                let distanceInMiles: Double = distanceInMeters * 0.00062137
                let distanceLabelText = String(format: "%.2f miles away", distanceInMiles)

                self.uid = json["uid"].stringValue

                let usersReference = Database.database().reference(withPath: "users").queryOrderedByKey().queryEqual(toValue: uid)
                usersReference.observeSingleEvent(of: .value, with: { snapshot in
                    if let dict = snapshot.value as? NSDictionary {
                        let userInfo = dict.allValues[0]
                        let userJSON = JSON(userInfo)
                        name = userJSON["name"].stringValue

                    }
                    let post = Post(uid: uid, caption: caption, downloadURL: downloadURL, name: name, date: date, address: address, state: state, distance: distanceLabelText, postID: postID)

                    self.feeds.append(post)

                    // sort posts by date/distance
                    self.feeds.sort {$0.date.compare($1.date) == .orderedDescending}
                    self.feeds.sort {$0.distance.compare($1.distance) == .orderedAscending}
                    self.feedTableView.reloadData()

                })
            }
        }
        if refreshing {
            refreshControl?.endRefreshing()
        }
        MBProgressHUD.hide(for: self.view, animated: true)
    })
}

Body:
I'm pretty sure that the order query must precede the limit query.

let ref = Database.database().reference().child("posts").queryOrdered(byChild: "businessName").queryLimited(toFirst: 2)


问:
VSCode: Is it possible to suppress experimental decorator warnings
In VSCode, I get the error:

"Experimental support for decorators is a feature that is subject to change in a future release. Specify '--experimentalDecorators' to remove this warning."

I can add the --experimentalDecorators flag to my tasks.json file to remove this error on build, but I can't seem to remove it from my intellisense or error list when I load VSCode.

Is there a way to do this?

答:
Even when opening VSCode at the right level within your project you might still need an extra tsconfig file in your root. I now have a tsconfig in my project root (only containing php index and folders), ts folder (legacy typescript classes) and my src folder (vue components).

Don't forget to close the folder and to restart VSCode.


问:
Find single unique value in list of tuples

I have a list of key-value pairs in tuples, and it's known that one (and only one) of those tuples will contain a different value.  The keys are all different.  For example,

```<code>pairs = [
         ('John', 101991),
         ('Bob', 101991),
         ('Tom', 101997),
         ('Larry', 101991),
         ('Howard', 101991)
         ]
</code>```

I need to identify the key of the tuple with the different value.  It is not known whether this value will be larger or smaller than the others.

How can I accomplish this?

答:
You can use itertools.groupby:

```<code>import itertools
pairs = [
     ('John', 101991),
     ('Bob', 101991),
     ('Tom', 101997),
     ('Larry', 101991),
     ('Howard', 101991)
     ]
new_pairs = [(a, list(b)) for a, b in itertools.groupby(sorted(pairs, key=lambda x:x[-1]), key=lambda x:x[-1])]
new_val = [a for a, b in new_pairs if len(b) == 1]
</code>```

Output:

```<code>[101997]
</code>```

Edit: more efficient solution using dictionaries:

```<code>from collections import defaultdict
d = defaultdict(list)
for a, b in pairs:
   d[b].append(a)

new_val = [a for a, b in d.items() if len(b) == 1]
</code>```

Body:
I have a list of key-value pairs in tuples, and it's known that one (and only one) of those tuples will contain a different value.  The keys are all different.  For example,

pairs = [
         ('John', 101991),
         ('Bob', 101991),
         ('Tom', 101997),
         ('Larry', 101991),
         ('Howard', 101991)
         ]

I need to identify the key of the tuple with the different value.  It is not known whether this value will be larger or smaller than the others.

How can I accomplish this?

Body:
You can use itertools.groupby:

import itertools
pairs = [
     ('John', 101991),
     ('Bob', 101991),
     ('Tom', 101997),
     ('Larry', 101991),
     ('Howard', 101991)
     ]
new_pairs = [(a, list(b)) for a, b in itertools.groupby(sorted(pairs, key=lambda x:x[-1]), key=lambda x:x[-1])]
new_val = [a for a, b in new_pairs if len(b) == 1]

Output:

[101997]

Edit: more efficient solution using dictionaries:

from collections import defaultdict
d = defaultdict(list)
for a, b in pairs:
   d[b].append(a)

new_val = [a for a, b in d.items() if len(b) == 1]


问:
Beginner and C++ templates: Is it an how possible using C++ template make a class oriented to work with chars work with costume structures?
So I am quite wary new to C++ and I really do not understand templates and how to use tham thow I rad wikipedia and started reading like 2000 pages long book on C++... So I am probably way 2 impatient but I wonder If using C++ templates we can make for example such simple class pair work with costume structures instead of chars.

```<code>#include <iostream>
#include <vector>

// Boost
#include <boost/thread.hpp>

#ifndef _IGraphElementBase_h_
#define _IGraphElementBase_h_
#pragma once

using namespace std ;

class IGraphElementBase {

public:
    boost::thread GraphWorker;
    mutable boost::mutex GraphItemMutex;
    boost::condition_variable GraphItemMutexConditionVariable;
    int SleepTime;

    // Function for preparing class to work
    virtual void Init(){ SetSleepTime(1);}

    void SetSleepTime(int timeMS)
    {
        SleepTime = timeMS;
    }

    // Function for data update // word virtual makes it possible to overwrite it
    virtual void updateData(){}

    void StartThread()
    {
        GraphWorker = boost::thread(&IGraphElementBase::Call, this);
    }

    virtual void CleanAPI(){}

    virtual void Clean()
    {
        GraphWorker.interrupt();
        GraphWorker.join();
        CleanAPI();

    }
    virtual void CastData(){}

    //Here is a main class thread function in infinite loop it calls for updateData function
    void Call()
    {
        try
        {
            for(;;){
                boost::this_thread::sleep(boost::posix_time::milliseconds(SleepTime));
                boost::mutex::scoped_lock lock(GraphItemMutex);
                boost::this_thread::interruption_point() ;

                updateData();

                lock.unlock();
                CastData();
                GraphItemMutexConditionVariable.notify_one();
            }
        }
        catch (boost::thread_interrupted)
        {
            // Thread end
        }
    }
};

#endif // _IGraphElementBase_h_

#include "IGraphElementBase.h"

#ifndef _IGraphElement_h_
#define _IGraphElement_h_

using namespace std ;

class IGraphElement : public IGraphElementBase{

    // We should define prototype of functions that will be subscribers to our data
    typedef void FuncCharPtr(char*, int) ;

public:
    struct GetResultStructure
    {
        int length;
        char* ptr;
    };

    // initGet sets up a pointer holding a copy of pointer of data we want to return on Get() call
    void InitGet(char * pointerToUseInGetOperations, int pointerToUseInGetOperationsSize)
    {
        pointerToGet = pointerToUseInGetOperations;
        pointerToGetSize = pointerToUseInGetOperationsSize;
    }

    // Function for adding subscribers functions
    void Add(FuncCharPtr* f)
    {
        FuncVec.push_back(f);
    }

    // Returns pointer to copy of current graphItem processed data
    GetResultStructure Get()
    {
        boost::mutex::scoped_lock lock(GraphItemMutex);
        char * dataCopy = new char[pointerToGetSize];
        memcpy (dataCopy,pointerToGet,pointerToGetSize);
        lock.unlock();
        GraphItemMutexConditionVariable.notify_one();
        GetResultStructure result;
        result.ptr = dataCopy;
        result.length = pointerToGetSize;
        return result;
    }

    void Clean()
    {
        GraphWorker.interrupt();
        GraphWorker.join();
        CleanAPI();
        //delete[] pointerToGet;
        //pointerToGet = 0;

    }

    // Cast data to subscribers and clean up given pointer
    void CastData(){
        for (size_t i = 0 ; i < FuncVec.size() ; i++){
            char * dataCopy = new char[pointerToGetSize];
            memcpy (dataCopy,pointerToGet,pointerToGetSize);
            FuncVec[i] (dataCopy, pointerToGetSize) ;}
    }

    // Cast given data to subscribers and clean up given pointer
    void CastData(char * data, int length){
        for(size_t i = 0 ; i < FuncVec.size(); i++){
            char* dataCopy = new char[length];
            memcpy(dataCopy, data, length);
            FuncVec[i](dataCopy, length);
        }
    }

private:
    // Char pointer to hold a copy of pointer of data we want to return on Get() call
    char* pointerToGet;
    int pointerToGetSize;

    // Vector to hold subscribed functions
    vector<FuncCharPtr*> FuncVec ;

};
#endif // _IGraphElement_h_
</code>```

So what is most intresting for me in that classes in short:

```<code>-   typedef void FuncCharPtr(char*, int) ;
-   vector<FuncCharPtr*> FuncVec ;
-   functions like void CastData(char * data, int length)
</code>```

It is really wary intresting for me if it is possile to somehow using templates make my classes work with costume structures. So Is it possible and how to do such thing?

答:
Templates are a parameterization of a class. That is, instead of having a bunch of different classes such as

```<code>class myclass_int
{
   int x;
}

class myclass_double
{
   double x;
}
</code>```

etc...

if you can see the pattern, the only thing different is the type used, SO, we will use an abstract type called a template as a sort of place holder,

```<code>class myclass_T
{
    T x;
}
</code>```

THIS CLASS IS NOT A SINGLE CLASS BUT A WHOLE COLLECTION. If we replace T with int we get the first class and T with double we get the second.

But when we instantiate myclass_T we must then specify what T actually is(is it in an int, double, etc..)?

so we will define this parameterized class as

```<code>template <typename T>
class myclass
{
   T x;
}
</code>```

And use T as it we already new what it really was.

That one class represents all the possible classes you could make up that had specific types used(I gave 2 instances at the start).

Templates simply make it easier to define such classes. There are a lot more to it than that but it is the foundation of why they are useful. The way to think of a templated class is not as a class but as a "Super class". That is, a class that has the ability to take on different representations.

It's not a difficult concept BUT if you don't have a lot of experience with oop you might not really see why they are useful and think they make things more complex. But once you end up having to write very many similar classes that all only differ by the types used then you'll see why they are so useful(they are actually quite powerful because they end up being able to do a lot more).

Body:
So I am quite wary new to C++ and I really do not understand templates and how to use tham thow I rad wikipedia and started reading like 2000 pages long book on C++... So I am probably way 2 impatient but I wonder If using C++ templates we can make for example such simple class pair work with costume structures instead of chars.

#include <iostream>
#include <vector>

// Boost
#include <boost/thread.hpp>

#ifndef _IGraphElementBase_h_
#define _IGraphElementBase_h_
#pragma once

using namespace std ;

class IGraphElementBase {

public:
    boost::thread GraphWorker;
    mutable boost::mutex GraphItemMutex;
    boost::condition_variable GraphItemMutexConditionVariable;
    int SleepTime;

    // Function for preparing class to work
    virtual void Init(){ SetSleepTime(1);}

    void SetSleepTime(int timeMS)
    {
        SleepTime = timeMS;
    }

    // Function for data update // word virtual makes it possible to overwrite it
    virtual void updateData(){}

    void StartThread()
    {
        GraphWorker = boost::thread(&IGraphElementBase::Call, this);
    }

    virtual void CleanAPI(){}

    virtual void Clean()
    {
        GraphWorker.interrupt();
        GraphWorker.join();
        CleanAPI();

    }
    virtual void CastData(){}

    //Here is a main class thread function in infinite loop it calls for updateData function
    void Call()
    {
        try
        {
            for(;;){
                boost::this_thread::sleep(boost::posix_time::milliseconds(SleepTime));
                boost::mutex::scoped_lock lock(GraphItemMutex);
                boost::this_thread::interruption_point() ;

                updateData();

                lock.unlock();
                CastData();
                GraphItemMutexConditionVariable.notify_one();
            }
        }
        catch (boost::thread_interrupted)
        {
            // Thread end
        }
    }
};

#endif // _IGraphElementBase_h_

#include "IGraphElementBase.h"

#ifndef _IGraphElement_h_
#define _IGraphElement_h_

using namespace std ;

class IGraphElement : public IGraphElementBase{

    // We should define prototype of functions that will be subscribers to our data
    typedef void FuncCharPtr(char*, int) ;

public:
    struct GetResultStructure
    {
        int length;
        char* ptr;
    };

    // initGet sets up a pointer holding a copy of pointer of data we want to return on Get() call
    void InitGet(char * pointerToUseInGetOperations, int pointerToUseInGetOperationsSize)
    {
        pointerToGet = pointerToUseInGetOperations;
        pointerToGetSize = pointerToUseInGetOperationsSize;
    }

    // Function for adding subscribers functions
    void Add(FuncCharPtr* f)
    {
        FuncVec.push_back(f);
    }

    // Returns pointer to copy of current graphItem processed data
    GetResultStructure Get()
    {
        boost::mutex::scoped_lock lock(GraphItemMutex);
        char * dataCopy = new char[pointerToGetSize];
        memcpy (dataCopy,pointerToGet,pointerToGetSize);
        lock.unlock();
        GraphItemMutexConditionVariable.notify_one();
        GetResultStructure result;
        result.ptr = dataCopy;
        result.length = pointerToGetSize;
        return result;
    }

    void Clean()
    {
        GraphWorker.interrupt();
        GraphWorker.join();
        CleanAPI();
        //delete[] pointerToGet;
        //pointerToGet = 0;

    }

    // Cast data to subscribers and clean up given pointer
    void CastData(){
        for (size_t i = 0 ; i < FuncVec.size() ; i++){
            char * dataCopy = new char[pointerToGetSize];
            memcpy (dataCopy,pointerToGet,pointerToGetSize);
            FuncVec[i] (dataCopy, pointerToGetSize) ;}
    }

    // Cast given data to subscribers and clean up given pointer
    void CastData(char * data, int length){
        for(size_t i = 0 ; i < FuncVec.size(); i++){
            char* dataCopy = new char[length];
            memcpy(dataCopy, data, length);
            FuncVec[i](dataCopy, length);
        }
    }

private:
    // Char pointer to hold a copy of pointer of data we want to return on Get() call
    char* pointerToGet;
    int pointerToGetSize;

    // Vector to hold subscribed functions
    vector<FuncCharPtr*> FuncVec ;

};
#endif // _IGraphElement_h_

So what is most intresting for me in that classes in short:

-   typedef void FuncCharPtr(char*, int) ;
-   vector<FuncCharPtr*> FuncVec ;
-   functions like void CastData(char * data, int length)

It is really wary intresting for me if it is possile to somehow using templates make my classes work with costume structures. So Is it possible and how to do such thing?

Body:
Templates are a parameterization of a class. That is, instead of having a bunch of different classes such as

class myclass_int
{
   int x;
}

class myclass_double
{
   double x;
}

etc...

if you can see the pattern, the only thing different is the type used, SO, we will use an abstract type called a template as a sort of place holder,

class myclass_T
{
    T x;
}

THIS CLASS IS NOT A SINGLE CLASS BUT A WHOLE COLLECTION. If we replace T with int we get the first class and T with double we get the second.

But when we instantiate myclass_T we must then specify what T actually is(is it in an int, double, etc..)?

so we will define this parameterized class as

template <typename T>
class myclass
{
   T x;
}

And use T as it we already new what it really was.

That one class represents all the possible classes you could make up that had specific types used(I gave 2 instances at the start).

Templates simply make it easier to define such classes. There are a lot more to it than that but it is the foundation of why they are useful. The way to think of a templated class is not as a class but as a "Super class". That is, a class that has the ability to take on different representations.

It's not a difficult concept BUT if you don't have a lot of experience with oop you might not really see why they are useful and think they make things more complex. But once you end up having to write very many similar classes that all only differ by the types used then you'll see why they are so useful(they are actually quite powerful because they end up being able to do a lot more).


问:
amChart total values of graphics
I want to write all of the total values in some where in graphics. My graphics may be column or stacked chart. How can I calculate all summ values in data and write?

```<code>"dataProvider": [ {
    "country": "USA",
    "visits": 2025
  }, {
    "country": "China",
    "visits": 1882
  }, {
    "country": "Japan",
    "visits": 1809
  } ]
</code>```

Or stacked data

```<code>"dataProvider": [{
            "year": 2003,
            "europe": 2.5,
            "namerica": 2.5,
            "asia": 2.1,
            "lamerica": 0.3,
            "meast": 0.2,
            "africa": 0.1
        }, {
            "year": 2004,
            "europe": 2.6,
            "namerica": 2.7,
            "asia": 2.2,
            "lamerica": 0.3,
            "meast": 0.3,
            "africa": 0.1
        }, {
            "year": 2005,
            "europe": 2.8,
            "namerica": 2.9,
            "asia": 2.4,
            "lamerica": 0.3,
            "meast": 0.3,
            "africa": 0.1
        }]
</code>```

Column chart

Stacked chart

Or is it possible to write in legend like this: "General Sum: 1254"

答:
Set totalText in the value axis to generate a sum of the stack:

```<code>AmCharts.makeChart("chartdiv", {
  // ...
  valueAxes: [{
    // ...
    totalText: "Total: [[total]]"
  }],
  // ...
});
</code>```

Demo

For single columns, try periodValueText in the legend.

```<code>AmCharts.makeChart("chartdiv", {
  // ...
  legend: {
    // ...
    periodValueText: "Selection total: [[value.sum]]"
  }
  // ...
});
</code>```

Note this shows the sum of the columns in selected period/zoom for a particular graph.

Demo

Title: amChart total values of graphics

Body:
I want to write all of the total values in some where in graphics. My graphics may be column or stacked chart. How can I calculate all summ values in data and write?

"dataProvider": [ {
    "country": "USA",
    "visits": 2025
  }, {
    "country": "China",
    "visits": 1882
  }, {
    "country": "Japan",
    "visits": 1809
  } ]

Or stacked data

"dataProvider": [{
            "year": 2003,
            "europe": 2.5,
            "namerica": 2.5,
            "asia": 2.1,
            "lamerica": 0.3,
            "meast": 0.2,
            "africa": 0.1
        }, {
            "year": 2004,
            "europe": 2.6,
            "namerica": 2.7,
            "asia": 2.2,
            "lamerica": 0.3,
            "meast": 0.3,
            "africa": 0.1
        }, {
            "year": 2005,
            "europe": 2.8,
            "namerica": 2.9,
            "asia": 2.4,
            "lamerica": 0.3,
            "meast": 0.3,
            "africa": 0.1
        }]

Column chart

Stacked chart

Or is it possible to write in legend like this: "General Sum: 1254"

Body:
Set totalText in the value axis to generate a sum of the stack:

AmCharts.makeChart("chartdiv", {
  // ...
  valueAxes: [{
    // ...
    totalText: "Total: [[total]]"
  }],
  // ...
});

Demo

For single columns, try periodValueText in the legend.

AmCharts.makeChart("chartdiv", {
  // ...
  legend: {
    // ...
    periodValueText: "Selection total: [[value.sum]]"
  }
  // ...
});

Note this shows the sum of the columns in selected period/zoom for a particular graph.

Demo


问:
I google maps, s there a way to change the view from 'map' to 'earth' or 'satellite, in a http link?
How can i change the following hyperlink path, to show by default, the earth or satellite view in Google Maps?

http://maps.google.com/maps?f=q&hl=en&geocode=&q=36.070690,-95.807090%28LineStat%29

I realize that i can select the other options after the site is pulled up, but for the sofware i have developed, it will save an extra step for our customers if they could see it in a different view.

Thank you!

答:
For Directions/Places you can use the following hack:

```<code>https://www.google.de/maps/place/Washington+DC/data=!3m1!1e3
</code>```

The parameter /data=!3m1!1e3 switches the map to terrain.

Body:
For Directions/Places you can use the following hack:

https://www.google.de/maps/place/Washington+DC/data=!3m1!1e3

The parameter /data=!3m1!1e3 switches the map to terrain.


问:
How to convert existing Angular 4 project to webpack
It's longtime I am working on an angular 4 project. Today I want to convert it to webpack.

I spent many time looking for a tutorial to do that But I have not found it.

I tried to grasp this the documentation of angular webpack but i didn't ge steps to convert the project.

Can someone please indicate me steps to follow ?

Any suggestion will be appreciated.

Regards

答:
I am not sure of the reasons you want to make a switch to webpack from angular cli (guess your code is already using that). Personally, I always prefer using webpack directly rather than using angular cli. I believe that gives the developer more control. But, that comes with big responsibility (as is usual with great power) towards evaluating all the goods from angular cli that you are going to miss!

Anyway, here is a sample module that uses webpack instead of angular cli. It uses latest angular 5 but should work with angular 4 as well.


答:
or alternatively</p>

```<code>pairs = [
         ('John', 101991),
         ('Bob', 101991),
         ('Tom', 101997),
         ('Larry', 101991),
         ('Howard', 101991)
]

stat = {}
for k, v in pairs:
    if not v in stat: stat[v] = []
    stat[v].append((k, v))

for v in stat:
    if len(stat[v]) == 1:
        print(stat[v][0][0]) #prints the key 'Tom'
</code>```

Title: Find single unique value in list of tuples

Body:
or alternatively

pairs = [
         ('John', 101991),
         ('Bob', 101991),
         ('Tom', 101997),
         ('Larry', 101991),
         ('Howard', 101991)
]

stat = {}
for k, v in pairs:
    if not v in stat: stat[v] = []
    stat[v].append((k, v))

for v in stat:
    if len(stat[v]) == 1:
        print(stat[v][0][0]) #prints the key 'Tom'


问:
Bundling javascript files to watch with Gulp and Nodeman
I have the start and deploy tasks working the way I want them to but I am trying to figure out how to update public/js/bundle.js when I make a change in app.js so that it can be watched.

Here's what I got so far:

```<code>var gulp = require('gulp');
var streamify = require('gulp-streamify');
var uglify = require('gulp-uglify');
var transform = require('vinyl-source-stream');
var browserify = require('browserify');
var rename = require('gulp-rename');
var nodemon = require('gulp-nodemon');

var ios = browserify({
   entries:['app.js']
 });

const bundle = () => {

  process.env.NODE_ENV = 'production';

    ios.require('./app-ios.js', {expose:'appalias'})
      .bundle()
      .pipe(transform('bundle-ios.js'))
      .pipe(gulp.dest('./public/js'))
      .pipe(streamify(uglify()))
      .pipe(rename('bundle-ios.min.js'))
      .pipe(gulp.dest('./public/js'));

    return ios;
}

const start = () => {
  return nodemon({
    script: 'server.js',
    watch: ['server.js', 'public/js/*', 'public/index.html', 'public/css/*'],
    ext: 'js html css',
    env: { 'NODE_ENV': 'development' },
  });
}

// Start local server and watch bundles.
gulp.task('start', start);

// Build minified versions for prod.
gulp.task('deploy', bundle);
</code>```

答:
The fix was to watch all the individual javascript component and model files and add a compile task to the start task.</p>

```<code>// Bundle and minify for development, use development version of libraries.
const compile = () => {

  process.env.NODE_ENV = 'development';

  const bundleAndroidDev = ios.require('./app-ios.js', {expose:'appalias'})
    .bundle()
    .pipe(transform('bundle-ios.js'))
    .pipe(gulp.dest('./public/js'));

  return bundleIosDev;
}

// Start local server and watch for changes in compiled bundles.
const start = () => {
  return nodemon({
    script: 'server.js',
    watch: ['server.js', 'apps/appName/components/*', 'apps/appName/models/*', 'public/index.html', 'public/css/*'],
    ext: 'js html css',
    tasks: ['compile'],
    env: { 'NODE_ENV': 'development' }
  });
}

// Compile bundle's on save.
gulp.task('compile', compile);
</code>```

Body:
I have the start and deploy tasks working the way I want them to but I am trying to figure out how to update public/js/bundle.js when I make a change in app.js so that it can be watched.

Here's what I got so far:

var gulp = require('gulp');
var streamify = require('gulp-streamify');
var uglify = require('gulp-uglify');
var transform = require('vinyl-source-stream');
var browserify = require('browserify');
var rename = require('gulp-rename');
var nodemon = require('gulp-nodemon');

var ios = browserify({
   entries:['app.js']
 });

const bundle = () => {

  process.env.NODE_ENV = 'production';

    ios.require('./app-ios.js', {expose:'appalias'})
      .bundle()
      .pipe(transform('bundle-ios.js'))
      .pipe(gulp.dest('./public/js'))
      .pipe(streamify(uglify()))
      .pipe(rename('bundle-ios.min.js'))
      .pipe(gulp.dest('./public/js'));

    return ios;
}

const start = () => {
  return nodemon({
    script: 'server.js',
    watch: ['server.js', 'public/js/*', 'public/index.html', 'public/css/*'],
    ext: 'js html css',
    env: { 'NODE_ENV': 'development' },
  });
}

// Start local server and watch bundles.
gulp.task('start', start);

// Build minified versions for prod.
gulp.task('deploy', bundle);

Body:
The fix was to watch all the individual javascript component and model files and add a compile task to the start task.

// Bundle and minify for development, use development version of libraries.
const compile = () => {

  process.env.NODE_ENV = 'development';

  const bundleAndroidDev = ios.require('./app-ios.js', {expose:'appalias'})
    .bundle()
    .pipe(transform('bundle-ios.js'))
    .pipe(gulp.dest('./public/js'));

  return bundleIosDev;
}

// Start local server and watch for changes in compiled bundles.
const start = () => {
  return nodemon({
    script: 'server.js',
    watch: ['server.js', 'apps/appName/components/*', 'apps/appName/models/*', 'public/index.html', 'public/css/*'],
    ext: 'js html css',
    tasks: ['compile'],
    env: { 'NODE_ENV': 'development' }
  });
}

// Compile bundle's on save.
gulp.task('compile', compile);


问:
Match and replace misspelled words in a string in R
I have a list of phrases, in which I want to replace certain words with a similar word, in case it is misspelled.

```<code>library(stringr)
a4 <- "I would like a cheseburger and friees please"
badwords.corpus <- c("cheseburger", "friees")
goodwords.corpus <- c("cheeseburger", "fries")

vect.corpus <- goodwords.corpus
names(vect.corpus) <- badwords.corpus

str_replace_all(a4, vect.corpus)
# [1] "I would like a cheeseburger and fries please"
</code>```

everything works perfectly, until it finds a similar string, and replaces it with another word

if I have a pattern like the following:

"plea", the correct one is "please", but when I execute it removes it and replaces it with "pleased".

What I am looking for is that if a string is already correct, it is no longer modified, in case it finds a similar pattern.

答:
Perhaps you need to perform progressive replace. e.g. you should have multiple set of badwords and goodwords. First replace with badwords having more letters so that matching pattern is not found and then got go for smaller ones.

From the list provided by you, I would create 2 sets as:

```<code>goodwords1<-c( "three", "teasing")
badwords1<- c("thre", "teeasing")

goodwords2<-c("tree", "testing")
badwords2<- c("tre", "tesing")
</code>```

First replace with 1st set and then with 2nd set. You can create many such sets.

Body:
I have a list of phrases, in which I want to replace certain words with a similar word, in case it is misspelled.

library(stringr)
a4 <- "I would like a cheseburger and friees please"
badwords.corpus <- c("cheseburger", "friees")
goodwords.corpus <- c("cheeseburger", "fries")

vect.corpus <- goodwords.corpus
names(vect.corpus) <- badwords.corpus

str_replace_all(a4, vect.corpus)
# [1] "I would like a cheeseburger and fries please"

everything works perfectly, until it finds a similar string, and replaces it with another word

if I have a pattern like the following:

"plea", the correct one is "please", but when I execute it removes it and replaces it with "pleased".

What I am looking for is that if a string is already correct, it is no longer modified, in case it finds a similar pattern.

Body:
Perhaps you need to perform progressive replace. e.g. you should have multiple set of badwords and goodwords. First replace with badwords having more letters so that matching pattern is not found and then got go for smaller ones.

From the list provided by you, I would create 2 sets as:

goodwords1<-c( "three", "teasing")
badwords1<- c("thre", "teeasing")

goodwords2<-c("tree", "testing")
badwords2<- c("tre", "tesing")

First replace with 1st set and then with 2nd set. You can create many such sets.


问:
Creating arrays dynamically using PHP
Hey folks, please lend a hand to a PHP beginner. I'm trying to put a load of dynamically created variabled into an array to re-read later, reason is a SOAP message sent is a mess and im trying to create a less complicated array:

```<code>$placea = "place a";
$placeb = "place b";

$myarray = array();

echo "```";
print_r($myarray);
echo "```";
</code>```

what i want to be able to do:

```<code>Array
(
    [0] => [Place A] => Array
        (
            [0] => [Accommodation] => Array
                (
                    [RoomId] => 001
                    [RoomAvail] => true
                    [Date] => 12.04.2011

                )
            [1] => [Accommodation] => Array
                (
                    [RoomId] => 002
                    [RoomAvail] => true
                    [Date] => 12.04.2011

                )

        )    Array
(
    [1] => [Place B] => Array
        (
            [0] => [Accommodation] => Array
                (
                    [RoomId] => 101
                    [RoomAvail] => true
                    [Date] => 12.04.2011

                )
            [1] => [Accommodation] => Array
                (
                    [RoomId] => 102
                    [RoomAvail] => true
                    [Date] => 12.04.2011

                )

        )

)
</code>```

how would i write that out in php? sorry if its bleek and/or the array structure is incorrect

答:
This would dynamically create an array. </p>

```<code>foreach($soapResponse as $key1 => $value1){
    foreach($value as $key2 => $value2){
        // $key1 = Place A or B
        // value1 = array of values
        $arrayResponse[$key1][$key2] =  $value2;
    }
}
</code>```

Title: Creating arrays dynamically using PHP

Body:
Hey folks, please lend a hand to a PHP beginner. I'm trying to put a load of dynamically created variabled into an array to re-read later, reason is a SOAP message sent is a mess and im trying to create a less complicated array:

$placea = "place a";
$placeb = "place b";

$myarray = array();

echo "
";
print_r($myarray);
echo "
";

what i want to be able to do:

Array
(
    [0] => [Place A] => Array
        (
            [0] => [Accommodation] => Array
                (
                    [RoomId] => 001
                    [RoomAvail] => true
                    [Date] => 12.04.2011

                )
            [1] => [Accommodation] => Array
                (
                    [RoomId] => 002
                    [RoomAvail] => true
                    [Date] => 12.04.2011

                )

        )    Array
(
    [1] => [Place B] => Array
        (
            [0] => [Accommodation] => Array
                (
                    [RoomId] => 101
                    [RoomAvail] => true
                    [Date] => 12.04.2011

                )
            [1] => [Accommodation] => Array
                (
                    [RoomId] => 102
                    [RoomAvail] => true
                    [Date] => 12.04.2011

                )

        )

)

how would i write that out in php? sorry if its bleek and/or the array structure is incorrect

Body:
This would dynamically create an array.

foreach($soapResponse as $key1 => $value1){
    foreach($value as $key2 => $value2){
        // $key1 = Place A or B
        // value1 = array of values
        $arrayResponse[$key1][$key2] =  $value2;
    }
}