问:
Opengl/glsl/lwjgl either 2d or 3d, not both?
So I'm trying to render a basic overlay onto my 3D scene, and currently I can either have the 3D scene or the 2D overlay, I cant work out how to get both

In my main method, where render is called, I moved specific render functions to manager classes, so in the main render I call :

```<code>        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glEnable(GL_DEPTH_TEST);
        glEnable(GL_COLOR_MATERIAL);

        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();

        glOrtho(-aspect, aspect, -1, 1, -10, 10);

        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

        material.setColour(new Vector3f(1,1,1));
        sLight.getPointLight().setPosition(camera.getPosition());
        sLight.setDirection(camera.getForward());

        DayCycle.getInstance().update(Time.getDelta());

        shader.updateUniforms(transform.getTransformation(), transform.getProjectedTransformation(), material);
        //material is a wrapper class for textures and specular value etc
        //transform is a matrix wrapper for getting projected transformations, taking the camera position when its created
        WorldManager.renderAll(true); //true denotes yes to wireframe mode

        InterfaceManager.renderAll();

        glfwSwapBuffers(window);
        glfwPollEvents();
</code>```

If i comment out WorldManager.renderAll(), I get the little 2d square in the right part of the screen, If i dont comment it, I get the world render but no little square

WorldManager.renderAll()

```<code>    public static void renderAll(boolean wireframeMode)
    {
    RendererUtils.setWireframeMode(wireframeMode);

    for (String s : chunks.keySet())
    {
        Chunk actingChunk = chunks.get(s);

        Transform transform = new Transform();
        Shader shader = PhongShader.getInstance();
        transform.setTranslation(new Vector3f(actingChunk.getLocation().getX() * (Chunk.ChunkSize),0.0f, actingChunk.getLocation().getY() * (Chunk.ChunkSize)));
        transform.setScale(1.0f, 50f, 1.0f);
        shader.updateUniforms(transform.getTransformation(), transform.getProjectedTransformation(), actingChunk.getMaterial());
        shader.bind();

        actingChunk.getMesh().draw();
        //transform.setRotation(new Vector3f(0,0,0));
    }
    }
</code>```

InterfaceManager.renderAll()

```<code>    public static void renderAll()
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    glOrtho(0, width, 0, height, -10, 10);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glDisable(GL_CULL_FACE);
    glDisable(GL_DEPTH_TEST);
    RendererUtils.setWireframeMode(false);
    for (Interface i : interfaces)
    {
        Transform transform = new Transform();
        transform.setTranslation(new Vector3f(0,0,0));
        InterfaceShader.getInstance().updateUniforms(transform.getProjectedTransformation());
        InterfaceShader.getInstance().bind();

        i.getMesh().draw();
    }
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
}
</code>```

When I have WorldManager.renderAll() uncommented, i get a nice sea of triangles (as its meant to look) but no 2D square
With it commented, I get a nice little square where its meant to be and nothing else

Shaders are here : https://pastebin.com/xWaWhQHy because I felt this post was getting too long to have them inlined

What's my problem? I cant figure out where it is

Edit : If i've missed any pertinent code, tell me and i'll upload it to a pastebin

Edit 2 : updated my code here to reflect that i'd removed a shader in interfaceManager to actually get a square to draw at all : https://pastebin.com/pHHDsCvF for the shader code

Edit 3 : Ive determined it's something to do with my interface shaders, If i use PhongShader instead of InterfaceShader then it works exactly how I wanted it to

答:
The problem was that I was still applying transformations to the vertices after passing them to the shader.

By editing out the transformation (and later scrapping the entire vertex shader) in the InterfaceShader instance, the little squares were appearing in the right place

Body:
So I'm trying to render a basic overlay onto my 3D scene, and currently I can either have the 3D scene or the 2D overlay, I cant work out how to get both

In my main method, where render is called, I moved specific render functions to manager classes, so in the main render I call :

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glEnable(GL_DEPTH_TEST);
        glEnable(GL_COLOR_MATERIAL);

        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();

        glOrtho(-aspect, aspect, -1, 1, -10, 10);

        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();

        material.setColour(new Vector3f(1,1,1));
        sLight.getPointLight().setPosition(camera.getPosition());
        sLight.setDirection(camera.getForward());

        DayCycle.getInstance().update(Time.getDelta());

        shader.updateUniforms(transform.getTransformation(), transform.getProjectedTransformation(), material);
        //material is a wrapper class for textures and specular value etc
        //transform is a matrix wrapper for getting projected transformations, taking the camera position when its created
        WorldManager.renderAll(true); //true denotes yes to wireframe mode

        InterfaceManager.renderAll();

        glfwSwapBuffers(window);
        glfwPollEvents();

If i comment out WorldManager.renderAll(), I get the little 2d square in the right part of the screen, If i dont comment it, I get the world render but no little square

WorldManager.renderAll()

    public static void renderAll(boolean wireframeMode)
    {
    RendererUtils.setWireframeMode(wireframeMode);

    for (String s : chunks.keySet())
    {
        Chunk actingChunk = chunks.get(s);

        Transform transform = new Transform();
        Shader shader = PhongShader.getInstance();
        transform.setTranslation(new Vector3f(actingChunk.getLocation().getX() * (Chunk.ChunkSize),0.0f, actingChunk.getLocation().getY() * (Chunk.ChunkSize)));
        transform.setScale(1.0f, 50f, 1.0f);
        shader.updateUniforms(transform.getTransformation(), transform.getProjectedTransformation(), actingChunk.getMaterial());
        shader.bind();

        actingChunk.getMesh().draw();
        //transform.setRotation(new Vector3f(0,0,0));
    }
    }

InterfaceManager.renderAll()

    public static void renderAll()
{
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();

    glOrtho(0, width, 0, height, -10, 10);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glDisable(GL_CULL_FACE);
    glDisable(GL_DEPTH_TEST);
    RendererUtils.setWireframeMode(false);
    for (Interface i : interfaces)
    {
        Transform transform = new Transform();
        transform.setTranslation(new Vector3f(0,0,0));
        InterfaceShader.getInstance().updateUniforms(transform.getProjectedTransformation());
        InterfaceShader.getInstance().bind();

        i.getMesh().draw();
    }
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
}

When I have WorldManager.renderAll() uncommented, i get a nice sea of triangles (as its meant to look) but no 2D square
With it commented, I get a nice little square where its meant to be and nothing else

Shaders are here : https://pastebin.com/xWaWhQHy because I felt this post was getting too long to have them inlined

What's my problem? I cant figure out where it is

Edit : If i've missed any pertinent code, tell me and i'll upload it to a pastebin

Edit 2 : updated my code here to reflect that i'd removed a shader in interfaceManager to actually get a square to draw at all : https://pastebin.com/pHHDsCvF for the shader code

Edit 3 : Ive determined it's something to do with my interface shaders, If i use PhongShader instead of InterfaceShader then it works exactly how I wanted it to


来源: stackexchange

问:
Validating against checkbox and aspnet validation
I'm using asp.net validation controls which work fine. I've since introduced an HTML checkbox which should be ticked before the form can be submitted.  My function for this reads as follows:

```<code>function terms(form) {
var terms = document.getElementById("chkTerms").checked;
var errorsArray = new Array();

if (terms == false) {
    //alert("Terms not checked (works)");
    errorsArray.push("You must agree to the terms and conditions.");
    if (errorsArray.length) {
        document.getElementById("termsOutput").innerHTML = errorsArray.join("\n") + "<br />";
        return false;
    }
}
else {
    document.getElementById("termsOutput").innerHTML = "";
}}
</code>```

It is called as follows:

```<code><asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="return terms(form)" />
</code>```

The problem I have is seems I can either use the asp.net validation OR the custom checkbox validation I wrote. After the form posts however, the asp.net validation fires!  Anyone know what I'm doing wrong?

答:
The ASP.NET button control uses the WebForm_DoPostBackWithOptions method that subsequently triggers the client-side validation.  By Adding return terms(form) to your button client click handler, this statement returns before the postback statement runs (which calls Page_ClientValidate) and so you don't see the validation.  Doing an (if !terms(form)) return false) instead will cancel only when false.

HTH.

ContentLicense: CC BY-SA 2.5

Body:
I'm using asp.net validation controls which work fine. I've since introduced an HTML checkbox which should be ticked before the form can be submitted.  My function for this reads as follows:

function terms(form) {
var terms = document.getElementById("chkTerms").checked;
var errorsArray = new Array();

if (terms == false) {
    //alert("Terms not checked (works)");
    errorsArray.push("You must agree to the terms and conditions.");
    if (errorsArray.length) {
        document.getElementById("termsOutput").innerHTML = errorsArray.join("\n") + "
";
        return false;
    }
}
else {
    document.getElementById("termsOutput").innerHTML = "";
}}

It is called as follows:

<asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClientClick="return terms(form)" />

The problem I have is seems I can either use the asp.net validation OR the custom checkbox validation I wrote. After the form posts however, the asp.net validation fires!  Anyone know what I'm doing wrong?


问:
I am getting gradle error Execution failed for task
I am getting this error

```<code>Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/android/volley/AuthFailureError.class
</code>```

I attached my gradle please check and help me.

```<code>    android {
              useLibrary 'org.apache.http.legacy'
             }

       dependencies {

    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile files('libs/android-async-http-1.4.4.jar')
    compile files('libs/disklrucache-2.0.1.jar')
    compile files('libs/google-gson.jar')
    compile project(':linkedin-sdk')
    compile files('libs/PGSDK_V2.0.jar')
    compile 'com.android.support:support-v13:25.3.1'
    compile files('libs/okhttp-1.2.1-jar-with-dependencies.jar')
    compile files('libs/volley.jar')
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'uk.co.chrisjenx:calligraphy:2.2.0'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:support-v4:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.razorpay:checkout:1.4.1'
    compile 'com.google.android.gms:play-services-auth:9.2.1'

    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'com.jjoe64:graphview:4.2.0'

}
</code>```

答:
Error:Execution failed for task
  ':app:transformClassesWithJarMergingForDebug'.>
  com.android.build.api.transform.TransformException:
  java.util.zip.ZipException: duplicate entry:
  com/android/volley/AuthFailureError.class

Remove

```<code> compile files('libs/volley.jar') // From local lib also
</code>```

Use

```<code>compile 'com.android.volley:volley:1.0.0'
</code>```

I am using linkedin sdk,inside linkedin adk also one volley compile is
  there and my app level I have one more volley dependency.

You should call volley:1.0.0 there.

ContentLicense: CC BY-SA 3.0

Body:
I am getting this error

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'.> com.android.build.api.transform.TransformException: java.util.zip.ZipException: duplicate entry: com/android/volley/AuthFailureError.class

I attached my gradle please check and help me.

    android {
              useLibrary 'org.apache.http.legacy'
             }

       dependencies {

    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile files('libs/android-async-http-1.4.4.jar')
    compile files('libs/disklrucache-2.0.1.jar')
    compile files('libs/google-gson.jar')
    compile project(':linkedin-sdk')
    compile files('libs/PGSDK_V2.0.jar')
    compile 'com.android.support:support-v13:25.3.1'
    compile files('libs/okhttp-1.2.1-jar-with-dependencies.jar')
    compile files('libs/volley.jar')
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:cardview-v7:25.3.1'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    compile 'uk.co.chrisjenx:calligraphy:2.2.0'
    compile 'com.android.support:design:25.3.1'
    compile 'com.android.support:support-v4:25.3.1'
    testCompile 'junit:junit:4.12'
    compile 'com.razorpay:checkout:1.4.1'
    compile 'com.google.android.gms:play-services-auth:9.2.1'

    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    compile 'com.jjoe64:graphview:4.2.0'

}

Body:
Error:Execution failed for task
  ':app:transformClassesWithJarMergingForDebug'.>
  com.android.build.api.transform.TransformException:
  java.util.zip.ZipException: duplicate entry:
  com/android/volley/AuthFailureError.class

Remove

 compile files('libs/volley.jar') // From local lib also

Use

compile 'com.android.volley:volley:1.0.0'

I am using linkedin sdk,inside linkedin adk also one volley compile is
  there and my app level I have one more volley dependency.

You should call volley:1.0.0 there.


问:
Javascript-friendly preprocessor dilemma
I've been working on a (nearly finished) Javascript project for a little over 14 months now. The project started out as a hack I expected to finish overnight, but over time the Javascript part has grown up to be 68 separate files and 10,314 non-empty lines, sadly currently dependent on the C preprocessor for building.

It's hard to explain how I ended up using cpp for the Javascript: this was only a hack, and I needed something that gave me macro expansion, ifdef, define, and includes without too much effort. After about 3 second's consideration, I realized cpp was "perfect" for the task:

Provide a LOG() macro that disappears in release mode.

Provide an ASSERT() macro that disappears in release mode, and generates exceptions tagged with original file and line number.

Swap LOG() and ASSERT() implementations for code that allows producing a "checked" build, which logs events in a compact form as they occur, that are reported back to the server if a crash occurs.

Replacing PROJECT_SOME_CONFIG_VAR_NAME with "1", based on a configuration file shared with the Python backend.

Like all true hacks, this hack is now so hard-coded into the project that I truly hate to even think about the work that will be required to replace it. My project is reaching the stage where I want to move the code base to its own dedicated test server (rather than my laptop), however on setting up a Linux instance, I've discovered that GNU cpp versions after 4.1 no longer preprocess the Javascript with crashing out with an error.

Rather than add a specific version of GCC to the list of build requirements, I figured now would be a good time to truly fix this mess. My problem is, though, that I can't find a replacement preprocessor with the same power and features as cpp! I have considered m4, but m4 is a world of pain unto itself. Other Javascript-specific preprocessors I have found lack all the features I am currently depending on, e.g.:

__FILE__ & __LINE__

Variadic macros

Include guards

Token concatenation

Conditional compilation

I am seriously considering implementing a brand new preprocessor just for Javascript, that completely borrows the C preprocessor syntax since it has worked so well. I'm just wondering if there are better options before doing so. :)  Perhaps there is already a cpp-like generic preprocessor I could swap in? The work required to replace all the preprocessor syntax in those 68 files approaches the amount of work required to simply reimplement the preprocessor.

I'm quite surprised I ever made it so far while relying on the C preprocessor; it is more effective at this task than healthy for the mind to comprehend. Another option open to me is statically building versions of cpp-4.1 for Linux, Darwin-i386, Win32, and storing those binaries in the project's repository.

Help!

答:
I looked at cpp and a few other contenders based on answers to similar questions. Then found what I think is the best answer by far - PHP. Consider:

1) PHP is indeed a preprocessor (its in the acronym).

2) PHP is ready to go on most servers. All you have to do is either change your file extensions from ".js" to ".php" or ".js.php", or (my preference) make a simple edit to a server config file (you can find the details elsewhere).

3) Many JavaScript developers are already familiar with or expert at PHP.

4) PHP is Turing-complete, unlike many other preprocessors.

5) You only need basic PHP knowledge to benefit a lot.

6) There is way more documentation/tutorials/forums for PHP than other preprocessors.

But mostly, it's so weird it's cool. Thanks to whoever gave me the idea - I can't find their post at the moment.


问:
Zk framework 6.5.3 binding with composer using E.L
I am using this code. Which is working very good.

```<code><window id="win" xmlns:w="http://www.zkoss.org/2005/zk/client" apply='MyComposer'>
<textbox value="@{$composer.student.name}"/>
</code>```

But i want to use something like this

```<code><cell width='$composer.fullWidth?"70%":"50%"'>
</code>```

In my composer I have a boolean fullWidth with the proper getter but I cannot reference it with the composer. I have tried a lot but nothing seems to work.

I have try

```<code><cell width='@{$composer.fullWidth}?"70%":"50%"'>
<cell width='{$composer.fullWidth}?"70%":"50%"'>
<cell width='@{composer.fullWidth}?"70%":"50%"'>
</code>```

Another question: if I have a code like this:

```<code><textbox id='test' if='expression'/>
</code>```

How can I the or use the if using Java code? Is it not possible?

Something like:

```<code>test.setIf(boolean???????)
</code>```

答:
First of all, please use correct MVVM.

The @{} is a buggy version from zk6.0 to created MVVM.

You even can't find that back in the ZK documentation!

With real MVVM :

```<code>@load(vm.fullwidth?'70%':'50%')
</code>```

Second question:

The if attribute a special one. Only static binding works here because if it's evaluated false, the component will not been rendered in the DOM.

So either use visible, or use in javacode an extra check if you may add this component to the DOM.

ContentLicense: CC BY-SA 4.0

Body:
I am using this code. Which is working very good.

<window id="win" xmlns:w="http://www.zkoss.org/2005/zk/client" apply='MyComposer'>
<textbox value="@{$composer.student.name}"/>

But i want to use something like this

<cell width='$composer.fullWidth?"70%":"50%"'>

In my composer I have a boolean fullWidth with the proper getter but I cannot reference it with the composer. I have tried a lot but nothing seems to work.

I have try

<cell width='@{$composer.fullWidth}?"70%":"50%"'>
<cell width='{$composer.fullWidth}?"70%":"50%"'>
<cell width='@{composer.fullWidth}?"70%":"50%"'>

Another question: if I have a code like this:

<textbox id='test' if='expression'/>

How can I the or use the if using Java code? Is it not possible?

Something like:

test.setIf(boolean???????)

Body:
First of all, please use correct MVVM.

The @{} is a buggy version from zk6.0 to created MVVM.

You even can't find that back in the ZK documentation!

With real MVVM :

@load(vm.fullwidth?'70%':'50%')

Second question:

The if attribute a special one. Only static binding works here because if it's evaluated false, the component will not been rendered in the DOM.

So either use visible, or use in javacode an extra check if you may add this component to the DOM.


问:
Unable to open PDF after it's generated (vb.net) (asp.net)
Sorry for this question, but I'm new in .net and vb.net. I really need your help! I generate a PDF file in asp.net (vb.net). It should be opened in a browser automatically, but it gives an error - Failed to load PDF document. I see it's created on a drive and opens properly. What could be an issue?

```<code>Protected Sub ExportToPDF(sender As Object, e As EventArgs)

    Response.ContentType = "application/pdf"
    Dim pdfDoc As New Document(PageSize.A4, 50.0F, 10.0F, 10.0F, 10.0F)
    PdfWriter.GetInstance(pdfDoc, New
       FileStream(Context.Server.MapPath("~/ejik.pdf"), FileMode.CreateNew))
    pdfDoc.Open()
    pdfDoc.Add(New Paragraph("What is going on?"))
    pdfDoc.Close()
    Response.Write(pdfDoc)
    Response.End()

End Sub
</code>```

Thank you in advance!

P.S.: Sorry, I forgot to mention that I use iTextSharp to create a PDF

答:
Your code is all wrong. You are creating a web application, and you create an object of type Document so that you can write a PDF file to disk. (Do you even need that file on disk? You are writing a web application!) Then, instead of sending the file to the end user, you write a Document object to the Response instead of (the bytes of) the file. That can never work, can it?

It would be better if you created the PDF file in memory first:

```<code>MemoryStream ms = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, ms);
document.Open();
document.Add(Assinatura());
document.Close();
</code>```

Then you take the bytes of that file in memory, and send them to the Response:

```<code>byte[] bytes = ms.ToArray();
ms.Close();
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;filename=ejik.pdf");
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();
</code>```

This is what the comment meant. Instead of pdfDoc, you need to send the byte array of the PDF file. See also iTextSharp is producing a corrupt PDF with Response

Body:
Sorry for this question, but I'm new in .net and vb.net. I really need your help! I generate a PDF file in asp.net (vb.net). It should be opened in a browser automatically, but it gives an error - Failed to load PDF document. I see it's created on a drive and opens properly. What could be an issue?

Protected Sub ExportToPDF(sender As Object, e As EventArgs)

    Response.ContentType = "application/pdf"
    Dim pdfDoc As New Document(PageSize.A4, 50.0F, 10.0F, 10.0F, 10.0F)
    PdfWriter.GetInstance(pdfDoc, New
       FileStream(Context.Server.MapPath("~/ejik.pdf"), FileMode.CreateNew))
    pdfDoc.Open()
    pdfDoc.Add(New Paragraph("What is going on?"))
    pdfDoc.Close()
    Response.Write(pdfDoc)
    Response.End()

End Sub

Thank you in advance!

P.S.: Sorry, I forgot to mention that I use iTextSharp to create a PDF

Body:
Your code is all wrong. You are creating a web application, and you create an object of type Document so that you can write a PDF file to disk. (Do you even need that file on disk? You are writing a web application!) Then, instead of sending the file to the end user, you write a Document object to the Response instead of (the bytes of) the file. That can never work, can it?

It would be better if you created the PDF file in memory first:

MemoryStream ms = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, ms);
document.Open();
document.Add(Assinatura());
document.Close();

Then you take the bytes of that file in memory, and send them to the Response:

byte[] bytes = ms.ToArray();
ms.Close();
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment;filename=ejik.pdf");
Response.Buffer = true;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
Response.End();

This is what the comment meant. Instead of pdfDoc, you need to send the byte array of the PDF file. See also iTextSharp is producing a corrupt PDF with Response


问:
Access to alias value in SQL Server 2012
I have a view with these columns:

```<code>id   date   Kcode   InOrder   pIn   SumIn   OutOrder   pOut   SumOut   stock  LastStock
</code>```

This view returns in/out of all goods order by kCode, date, id. It works very well, but I need a new column that returns the Average Cost of each row with this formula:

```<code> buyAvg =
    if lastStok = 0
    then buyAvg = pIn
    else
        if InOrder = 0 then
          if prev record Kcode = Kcode
           then buyAvg = Prev Record buyAvg
          else buyAvg = 0

        if InOrder <> 0 then
        if prev record Kcode = Kcode
           then buyAvg = ((sumIn) + (LastStok*Prev Record buyAvg)) / (inOrder+LastStock)
          else buyAvg = pIn
    end
</code>```

Thanks.

I need a view like in this screenshot that calculates BuyAvg:

答:
Better understood once you corrected the formula.
It is not easy to get the previous value for a calculated column in this case

So we can convert the calculated column into a physical column on a temporary table and use it later.

This code works but is not a good solution i think. If the old records do not change, I suggest you open a new physical column for buyAvg and it is a good idea to calculate and write it at during insert

UPDATED Query

```<code>select *, cast(null as Decimal(18,2)) as buyavg into #temp from dbo.YourTable where 1=2
;

DECLARE @id int
DECLARE @previd int
DECLARE @prvBuyAvg decimal(18,2)
DECLARE @prvKcode int
DECLARE db_cursor CURSOR FOR

SELECT Id, LAG(Id) OVER (ORDER BY Kcode,datee,id) prevId
FROM dbo.YourTable
order by Kcode,datee,id

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @id, @previd
WHILE @@FETCH_STATUS = 0
BEGIN
       select @prvKcode = Kcode, @prvBuyAvg = buyAvg
       from #temp where id = @previd

       insert into #temp  ([Id], [date], [Kcode] , [InOrder] , [pIn] , [SumIn] , OutOrder , pOut , SumOut , stock , LastStock , buyavg)
       select [Id], [date], [Kcode] , [InOrder] , [pIn] , [SumIn] , OutOrder , pOut , SumOut , stock , LastStock ,

       case
       when lastStock = 0 then
            pIn
       else
            case
            when InOrder = 0 then
                 case
                 when @prvKcode = Kcode then
                      @prvBuyAvg
                 else
                       0
                 end
            else
                 case
                 when @prvKcode = Kcode then
                      ((sumIn) + (LastStock*@prvBuyAvg)) / (inOrder+LastStock)
                 else
                      pIn
                 end
            end
       end as newbuyAvg
       from dbo.YourTable  where id = @id

       FETCH NEXT FROM db_cursor INTO @id, @previd
END
CLOSE db_cursor
DEALLOCATE db_cursor
;

select * from #temp
;
</code>```

Body:
I have a view with these columns:

id   date   Kcode   InOrder   pIn   SumIn   OutOrder   pOut   SumOut   stock  LastStock

This view returns in/out of all goods order by kCode, date, id. It works very well, but I need a new column that returns the Average Cost of each row with this formula:

 buyAvg =
    if lastStok = 0
    then buyAvg = pIn
    else
        if InOrder = 0 then
          if prev record Kcode = Kcode
           then buyAvg = Prev Record buyAvg
          else buyAvg = 0

        if InOrder <> 0 then
        if prev record Kcode = Kcode
           then buyAvg = ((sumIn) + (LastStok*Prev Record buyAvg)) / (inOrder+LastStock)
          else buyAvg = pIn
    end

Thanks.

I need a view like in this screenshot that calculates BuyAvg:

Body:
Better understood once you corrected the formula.
It is not easy to get the previous value for a calculated column in this case

So we can convert the calculated column into a physical column on a temporary table and use it later.

This code works but is not a good solution i think. If the old records do not change, I suggest you open a new physical column for buyAvg and it is a good idea to calculate and write it at during insert

UPDATED Query

select *, cast(null as Decimal(18,2)) as buyavg into #temp from dbo.YourTable where 1=2
;

DECLARE @id int
DECLARE @previd int
DECLARE @prvBuyAvg decimal(18,2)
DECLARE @prvKcode int
DECLARE db_cursor CURSOR FOR

SELECT Id, LAG(Id) OVER (ORDER BY Kcode,datee,id) prevId
FROM dbo.YourTable
order by Kcode,datee,id

OPEN db_cursor
FETCH NEXT FROM db_cursor INTO @id, @previd
WHILE @@FETCH_STATUS = 0
BEGIN
       select @prvKcode = Kcode, @prvBuyAvg = buyAvg
       from #temp where id = @previd

       insert into #temp  ([Id], [date], [Kcode] , [InOrder] , [pIn] , [SumIn] , OutOrder , pOut , SumOut , stock , LastStock , buyavg)
       select [Id], [date], [Kcode] , [InOrder] , [pIn] , [SumIn] , OutOrder , pOut , SumOut , stock , LastStock ,

       case
       when lastStock = 0 then
            pIn
       else
            case
            when InOrder = 0 then
                 case
                 when @prvKcode = Kcode then
                      @prvBuyAvg
                 else
                       0
                 end
            else
                 case
                 when @prvKcode = Kcode then
                      ((sumIn) + (LastStock*@prvBuyAvg)) / (inOrder+LastStock)
                 else
                      pIn
                 end
            end
       end as newbuyAvg
       from dbo.YourTable  where id = @id

       FETCH NEXT FROM db_cursor INTO @id, @previd
END
CLOSE db_cursor
DEALLOCATE db_cursor
;

select * from #temp
;


问:
How to get list of trending github repositories by github api?
I want get list of github trending repos like this -https://github.com/trending?l=java
but i didnt find any similar request methods at https://developer.github.com/v3/ , how can i get  json responce with trending repos? </p>

答:
Currently there is no GitHub API to get list of trending repositories. The only way is to crawl items from web page by selectors. You can open https://github.com/trending in Chrome and run the following code in devtools console:

```<code>$$('ol.repo-list li h3').forEach(el => console.log(el.innerText));
</code>```

This will output the list of trending repositories names. To make it more automated consider Headles Chrome or other similar tools.

Also there are several projects that already have solved this task in different languages. For example:

vitalets/github-trending-repos

andygrunwald/go-trending

sheharyarn/github-trending

etc

Body:
Currently there is no GitHub API to get list of trending repositories. The only way is to crawl items from web page by selectors. You can open https://github.com/trending in Chrome and run the following code in devtools console:

$$('ol.repo-list li h3').forEach(el => console.log(el.innerText));

This will output the list of trending repositories names. To make it more automated consider Headles Chrome or other similar tools.

Also there are several projects that already have solved this task in different languages. For example:

vitalets/github-trending-repos

andygrunwald/go-trending

sheharyarn/github-trending

etc


问:
Global $post shows null in some of my custom post types archive pages
My english is not very good looking.

I have several custom post types, 'noticias' (news) 'articulos' (articles), etc.
In my functions.php i enqueue scripts and styles by post_id or post_type using a code like this:

```<code>function mahg_scripts_by_page() {
    global $post;
    $page_id = $post->ID;
    $post_type = $post->post_type; // var_dump($post_type);

    $noti = 'noticia';      // POST-TYPE noticia
    $arti = 'articulo'; // POST-TYPE articulo
    $com1 = 4;              // that page id
    $com2 = 6;              // that other page id
 // $etc if i needed

    $front_commons = array($noti, $arti, $com1, $com2, $etc);
    if ( is_home() || is_404() || is_single() || in_array($page_id, $front_commons, true) ) {
        wp_register_style('uikit_css', get_template_directory_uri().'/css/uikit.css', array(), '', 'all' );
        wp_enqueue_style('uikit_css');
        wp_register_script('uikit_js', get_template_directory_uri().'/js/uikit.min.js','','', true );
        wp_enqueue_script('uikit_js');

    if (is_home() ) {
        wp_register_style('slideshow_css', get_template_directory_uri().'/css/components/slideshow.css', array(), '', 'all' );
        wp_enqueue_style('slideshow_css');
        wp_register_script('slideshow_js', get_template_directory_uri().'/js/components/slideshow.min.js','','', true );
        wp_enqueue_script('slideshow_js');
    }
    // more scripts or styles from here
}
add_action('wp_enqueue_scripts', 'mahg_scripts_by_page' );
</code>```

I created the archive-noticia.php and archive-articulo.php in my theme folder. But when run the website the browser load the scripts and styles in articulo archive page but in noticia archive page don't.
When i do var_dump($post_type); shows 'articulo' (length=8) in articulo archive page. But shows null in noticia archive page and the others custom post types.

When i did the register_post_type( 'articulo', $args);, has_archive was set true. Same in noticia.

```<code>$singular = 'Artículo';
$plural = 'Artículos';
$labels = array(
    'name'                  => $plural,
    'singular_name'         => $singular,
    'add_new'               => 'Nuevo ' . $singular,
    'add_new_item'          => 'Agregar nuevo ' . $singular,
    'edit'                  => 'Editar',
    'edit_item'             => 'Editar ' . $singular,
    'new_item'              => 'Nuevo ' . $singular,
    'view'                  => 'Ver ' . $singular,
    'view_item'             => 'Ver ' . $singular,
    'search_term'           => 'Buscar ' . $plural,
    'parent'                => 'Parent ' . $singular,
    'not_found'             => 'No se han encontrado ' . $plural,
    'not_found_in_trash'    => 'No hay ' . $plural .' en la papelera'
);
$args = array(
    'labels'              => $labels,
    'public'              => true,
    'publicly_queryable'  => true,
    'exclude_from_search' => false,
    'show_in_nav_menus'   => false,
    'show_ui'             => true,
    'show_in_menu'        => true,
    'show_in_admin_bar'   => false,
    'menu_position'       => 7,
    'menu_icon'           => 'dashicons-media-spreadsheet',
    'can_export'          => true,
    'delete_with_user'    => false,
    'hierarchical'        => true,
    'has_archive'         => true,
    'query_var'           => true,
    'capability_type'     => 'post',
    'map_meta_cap'        => true,
    'rewrite'             => true,
    'rewrite' => array(
        'slug'          => 'articulos',
        'with_front'    => true,
        'pages'         => true,
        'feeds'         => false,
    ),
    'supports' => array('title','editor','thumbnail','excerpt')
);
register_post_type( 'articulo', $args);

$singular = 'Noticia';
$plural = 'Noticias';
$labels = array(
    'name'                  => $plural,
    'singular_name'         => $singular,
    'add_new'               => 'Nueva ' . $singular,
    'add_new_item'          => 'Agregar nueva ' . $singular,
    'edit'                  => 'Editar',
    'edit_item'             => 'Editar ' . $singular,
    'new_item'              => 'Nueva ' . $singular,
    'view'                  => 'Ver ' . $singular,
    'view_item'             => 'Ver ' . $singular,
    'search_term'           => 'Buscar ' . $plural,
    'parent'                => 'Parent ' . $singular,
    'not_found'             => 'No se han encontrado ' . $plural,
    'not_found_in_trash'    => 'No hay ' . $plural .' en la papelera'
);
$args = array(
    'labels'              => $labels,
    'public'              => true,
    'exclude_from_search' => false,
    'publicly_queryable'  => true,
    'show_ui'             => true,
    'show_in_nav_menus'   => false,
    'show_in_menu'        => true,
    'show_in_admin_bar'   => false,
    'menu_position'       => 6,
    'menu_icon'           => 'dashicons-media-document',
    'capability_type'     => 'post',
    'map_meta_cap'        => true,
    'hierarchical'        => true,
    'supports'            => array('title','editor','thumbnail','excerpt'),
    'has_archive'         => true,
    'rewrite'             => true,
    'rewrite' => array(
            'slug'              => 'noticias',
            'with_front'        => true,
            'pages'             => true,
            'feeds'             => false,
    ),
    'query_var'           => true,
    'can_export'          => true,
    'delete_with_user'    => false,
);
register_post_type( 'noticia', $args);
</code>```

Why wordpress do that? What im doing wrong?

答: Please go to settings->permalinks and set it to "Post name". If it is set, Just click on "Save changes" button so that htaccess file will re-write.

Body:
My english is not very good looking.

I have several custom post types, 'noticias' (news) 'articulos' (articles), etc.
In my functions.php i enqueue scripts and styles by post_id or post_type using a code like this:

function mahg_scripts_by_page() {
    global $post;
    $page_id = $post->ID;
    $post_type = $post->post_type; // var_dump($post_type);

    $noti = 'noticia';      // POST-TYPE noticia
    $arti = 'articulo'; // POST-TYPE articulo
    $com1 = 4;              // that page id
    $com2 = 6;              // that other page id
 // $etc if i needed

    $front_commons = array($noti, $arti, $com1, $com2, $etc);
    if ( is_home() || is_404() || is_single() || in_array($page_id, $front_commons, true) ) {
        wp_register_style('uikit_css', get_template_directory_uri().'/css/uikit.css', array(), '', 'all' );
        wp_enqueue_style('uikit_css');
        wp_register_script('uikit_js', get_template_directory_uri().'/js/uikit.min.js','','', true );
        wp_enqueue_script('uikit_js');

    if (is_home() ) {
        wp_register_style('slideshow_css', get_template_directory_uri().'/css/components/slideshow.css', array(), '', 'all' );
        wp_enqueue_style('slideshow_css');
        wp_register_script('slideshow_js', get_template_directory_uri().'/js/components/slideshow.min.js','','', true );
        wp_enqueue_script('slideshow_js');
    }
    // more scripts or styles from here
}
add_action('wp_enqueue_scripts', 'mahg_scripts_by_page' );

I created the archive-noticia.php and archive-articulo.php in my theme folder. But when run the website the browser load the scripts and styles in articulo archive page but in noticia archive page don't.
When i do var_dump($post_type); shows 'articulo' (length=8) in articulo archive page. But shows null in noticia archive page and the others custom post types.

When i did the register_post_type( 'articulo', $args);, has_archive was set true. Same in noticia.

$singular = 'Artículo';
$plural = 'Artículos';
$labels = array(
    'name'                  => $plural,
    'singular_name'         => $singular,
    'add_new'               => 'Nuevo ' . $singular,
    'add_new_item'          => 'Agregar nuevo ' . $singular,
    'edit'                  => 'Editar',
    'edit_item'             => 'Editar ' . $singular,
    'new_item'              => 'Nuevo ' . $singular,
    'view'                  => 'Ver ' . $singular,
    'view_item'             => 'Ver ' . $singular,
    'search_term'           => 'Buscar ' . $plural,
    'parent'                => 'Parent ' . $singular,
    'not_found'             => 'No se han encontrado ' . $plural,
    'not_found_in_trash'    => 'No hay ' . $plural .' en la papelera'
);
$args = array(
    'labels'              => $labels,
    'public'              => true,
    'publicly_queryable'  => true,
    'exclude_from_search' => false,
    'show_in_nav_menus'   => false,
    'show_ui'             => true,
    'show_in_menu'        => true,
    'show_in_admin_bar'   => false,
    'menu_position'       => 7,
    'menu_icon'           => 'dashicons-media-spreadsheet',
    'can_export'          => true,
    'delete_with_user'    => false,
    'hierarchical'        => true,
    'has_archive'         => true,
    'query_var'           => true,
    'capability_type'     => 'post',
    'map_meta_cap'        => true,
    'rewrite'             => true,
    'rewrite' => array(
        'slug'          => 'articulos',
        'with_front'    => true,
        'pages'         => true,
        'feeds'         => false,
    ),
    'supports' => array('title','editor','thumbnail','excerpt')
);
register_post_type( 'articulo', $args);

$singular = 'Noticia';
$plural = 'Noticias';
$labels = array(
    'name'                  => $plural,
    'singular_name'         => $singular,
    'add_new'               => 'Nueva ' . $singular,
    'add_new_item'          => 'Agregar nueva ' . $singular,
    'edit'                  => 'Editar',
    'edit_item'             => 'Editar ' . $singular,
    'new_item'              => 'Nueva ' . $singular,
    'view'                  => 'Ver ' . $singular,
    'view_item'             => 'Ver ' . $singular,
    'search_term'           => 'Buscar ' . $plural,
    'parent'                => 'Parent ' . $singular,
    'not_found'             => 'No se han encontrado ' . $plural,
    'not_found_in_trash'    => 'No hay ' . $plural .' en la papelera'
);
$args = array(
    'labels'              => $labels,
    'public'              => true,
    'exclude_from_search' => false,
    'publicly_queryable'  => true,
    'show_ui'             => true,
    'show_in_nav_menus'   => false,
    'show_in_menu'        => true,
    'show_in_admin_bar'   => false,
    'menu_position'       => 6,
    'menu_icon'           => 'dashicons-media-document',
    'capability_type'     => 'post',
    'map_meta_cap'        => true,
    'hierarchical'        => true,
    'supports'            => array('title','editor','thumbnail','excerpt'),
    'has_archive'         => true,
    'rewrite'             => true,
    'rewrite' => array(
            'slug'              => 'noticias',
            'with_front'        => true,
            'pages'             => true,
            'feeds'             => false,
    ),
    'query_var'           => true,
    'can_export'          => true,
    'delete_with_user'    => false,
);
register_post_type( 'noticia', $args);

Why wordpress do that? What im doing wrong?


问:
.htaccess multiple parameters is not working
I have a problem with htaccess rule because is not working. I already try to find any solution on google but still have not found yet.
The code is:

```<code>RewriteEngine ON
RewriteBase /deshop/
RewriteCond %{REQUEST_URI} ^/deshop/admin(.+)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ admin/index.php [L,QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)$ index.php?p=$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/([^\s]+)$ index.php?p=$1&b=$2 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/([0-9]+)$ index.php?p=$1&id=$2 [L]
</code>```

The urls are working normally:

```<code>http://localhost/deshop/index.php to http://localhost/deshop/ -> home page from folder
http://localhost/deshop/admin/index.php to http://localhost/deshop/admin/ -> admin page from subfolder
http://localhost/deshop/index.php?p=tshirts to http://localhost/deshop/tshirts/
http://localhost/deshop/index.php?p=brand&b=John%20Player to http://localhost/deshop/brand/John-Player/
</code>```

So that happen, last rule does not work.

```<code>RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/([0-9]+)$ index.php?p=$1&id=$2 [L]
</code>```

But last rule has worked yet. I really difficult. I want get url with parameters so look work :

```<code>http://localhost/deshop/index.php?p=single&id=0005 to http://localhost/deshop/single/0005
</code>```

Or, what am I wrong? Any solution? Can you help me? Thanks a lot. By the way, my english is not good. I'm sorry!

答:
Finally I have solved it. </p>

```<code>RewriteEngine ON

RewriteCond %{REQUEST_URI} ^/miistore/miiadmin$
RewriteRule ^(.+)$ miiadmin/index.php [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ index.php?p=$1 [L,QSA]

RewriteRule ^/?single/([^/d]+)/?$ index.php?p=single&id=$1 [L,QSA]
RewriteRule ^/?brand/([^\s]+)/?$ index.php?p=brand&b=$1 [L,QSA]
</code>```

Body:
I have a problem with htaccess rule because is not working. I already try to find any solution on google but still have not found yet.
The code is:

RewriteEngine ON
RewriteBase /deshop/
RewriteCond %{REQUEST_URI} ^/deshop/admin(.+)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)$ admin/index.php [L,QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)$ index.php?p=$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/([^\s]+)$ index.php?p=$1&b=$2 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/([0-9]+)$ index.php?p=$1&id=$2 [L]

The urls are working normally:

http://localhost/deshop/index.php to http://localhost/deshop/ -> home page from folder
http://localhost/deshop/admin/index.php to http://localhost/deshop/admin/ -> admin page from subfolder
http://localhost/deshop/index.php?p=tshirts to http://localhost/deshop/tshirts/
http://localhost/deshop/index.php?p=brand&b=John%20Player to http://localhost/deshop/brand/John-Player/

So that happen, last rule does not work.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]*)/([0-9]+)$ index.php?p=$1&id=$2 [L]

But last rule has worked yet. I really difficult. I want get url with parameters so look work :

http://localhost/deshop/index.php?p=single&id=0005 to http://localhost/deshop/single/0005

Or, what am I wrong? Any solution? Can you help me? Thanks a lot. By the way, my english is not good. I'm sorry!

Body:
Finally I have solved it.

RewriteEngine ON

RewriteCond %{REQUEST_URI} ^/miistore/miiadmin$
RewriteRule ^(.+)$ miiadmin/index.php [L,QSA]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/?$ index.php?p=$1 [L,QSA]

RewriteRule ^/?single/([^/d]+)/?$ index.php?p=single&id=$1 [L,QSA]
RewriteRule ^/?brand/([^\s]+)/?$ index.php?p=brand&b=$1 [L,QSA]


问:
Having trouble using Arraylist.get method and it's showing "Incompatible operand types Object and int"
I was trying to take an unknown number of integers from the user (until the user enters 0), and count the number of occurrences of each of the integers entered. I figured, to count after I'm done taking the integers, I'd have to store them in an array. And I did some research and realized that the only way to create an Array with an unspecified length, ArrayList is the only way. But my this part of the code is showing error:</p>

```<code>import java.util.Scanner;

import java.util.ArrayList;

public class IntegersOccurence {

    public static void main(String[] args) {
        Scanner input = new Scanner (System.in);

        System.out.print("Enter the integers between 1 and 100: ");
        ArrayList list = new ArrayList();
        System.out.println(list.get(0));
        //eclipse is showing an error in the line right below
        while (list.get(list.size() - 1) != 0) {
            list.add(input.nextInt());
        }
    }
}
</code>```

答:
You Should better use this code:</p>

```<code>import java.util.List;
import java.util.Scanner;
import java.util.ArrayList;

public class IntegersOccurence {

    public static void main(String[] args) {
        Scanner input = new Scanner (System.in);

        System.out.print("Enter the integers between 1 and 100: ");
        List<Integer> list = new ArrayList<Integer>();
        list.add(input.nextInt());
        System.out.println(list.get(0));
        //eclipse is showing an error in the line right below
        while (list.get(list.size() - 1) != 0) {
            list.add(input.nextInt());
        }
    }
}
</code>```

Body:
I was trying to take an unknown number of integers from the user (until the user enters 0), and count the number of occurrences of each of the integers entered. I figured, to count after I'm done taking the integers, I'd have to store them in an array. And I did some research and realized that the only way to create an Array with an unspecified length, ArrayList is the only way. But my this part of the code is showing error:

import java.util.Scanner;

import java.util.ArrayList;

public class IntegersOccurence {

    public static void main(String[] args) {
        Scanner input = new Scanner (System.in);

        System.out.print("Enter the integers between 1 and 100: ");
        ArrayList list = new ArrayList();
        System.out.println(list.get(0));
        //eclipse is showing an error in the line right below
        while (list.get(list.size() - 1) != 0) {
            list.add(input.nextInt());
        }
    }
}

Body:
You Should better use this code:

import java.util.List;
import java.util.Scanner;
import java.util.ArrayList;

public class IntegersOccurence {

    public static void main(String[] args) {
        Scanner input = new Scanner (System.in);

        System.out.print("Enter the integers between 1 and 100: ");
        List<Integer> list = new ArrayList<Integer>();
        list.add(input.nextInt());
        System.out.println(list.get(0));
        //eclipse is showing an error in the line right below
        while (list.get(list.size() - 1) != 0) {
            list.add(input.nextInt());
        }
    }
}


问:
How do I write a "tab" in Python?
Let's say I have a file. How do I write "hello" TAB "alex"?</p>

答:
As it wasn't mentioned in any answers, just in case you want to align and space your text, you can use the string format features. (above python 2.5) Of course \t is actually a TAB token whereas the described method generates spaces.

Example:

```<code>print "{0:30} {1}".format("hi", "yes")
> hi                             yes
</code>```

Another Example, left aligned:

```<code>print("{0:<10} {1:<10} {2:<10}".format(1.0, 2.2, 4.4))
>1.0        2.2        4.4
</code>```

Title: How do I write a "tab" in Python?

Body:
As it wasn't mentioned in any answers, just in case you want to align and space your text, you can use the string format features. (above python 2.5) Of course \t is actually a TAB token whereas the described method generates spaces.

Example:

print "{0:30} {1}".format("hi", "yes")
> hi                             yes

Another Example, left aligned:

print("{0:<10} {1:<10} {2:<10}".format(1.0, 2.2, 4.4))
>1.0        2.2        4.4


问:
Read/see More at the end of the label
I am trying to create a read more button at the end of my label. I want it to display 3 lines by default. I am coding in swift not objective c. Only when the user clicks the read more part of the label, should the label expand. It should look and work exactly like it does on instagram except on Instagram, it is in a tableview cell. My label and read more button will be in a scrollview. I have managed to get the expanding and contracting part working by adjusting the number of lines property of the label.

```<code>if descriptionLabel.numberOfLines == 0{
    descriptionLabel.numberOfLines = 3
}else {
    descriptionLabel.numberOfLines = 0
}
descriptionLabel.lineBreakMode = NSLineBreakMode.byWordWrapping
</code>```

I am having problems with putting a "...more" at the end of the label and cutting the text off at the right place. I have looked at other people's responses to similar questions but nothing seems to work properly.

I can put a button over the last line of text so making the see more part of the label clickable also isn't the problem. The problem I am having is truncating the text at the right place and placing the see more text at the right place so that it displays.

I also want the read more button to only appear when it is necessary. I don't want to it appear when there are only 1-3 lines of text. This is also something I am having issues with.

I can't use this https://github.com/apploft/ExpandableLabel because it does not support scrollviews just tableviews.

the swift solution here didn't work: Add "...Read More" to the end of UILabel. It crashed the app.

Finally, the read more button should be in line with the last line of text and at the end of it. It would be an added benefit it this worked in a tableview cell as well!

答:
I found ReadMoreTextView in Github, which is based on UITextView. The key method in this library is the following:

```<code>private func characterIndexBeforeTrim(range rangeThatFits: NSRange) -> Int {
    if let text = attributedReadMoreText {
        let readMoreBoundingRect = attributedReadMoreText(text: text, boundingRectThatFits: textContainer.size)
        let lastCharacterRect = layoutManager.boundingRectForCharacterRange(range: NSMakeRange(NSMaxRange(rangeThatFits)-1, 1), inTextContainer: textContainer)
        var point = lastCharacterRect.origin
        point.x = textContainer.size.width - ceil(readMoreBoundingRect.size.width)
        let glyphIndex = layoutManager.glyphIndex(for: point, in: textContainer, fractionOfDistanceThroughGlyph: nil)
        let characterIndex = layoutManager.characterIndexForGlyph(at: glyphIndex)
        return characterIndex - 1
    } else {
        return NSMaxRange(rangeThatFits) - readMoreText!.length
    }
}
</code>```

To display text like "xxxx...Read More", the library

Get how many characters could be display in the UITextView: Use NSLayoutManager.characterRange(forGlyphRange:, actualGlyphRange:)

Get the position of the last visible character and the width of "...Read More": Use NSLayoutManager.boundingRect(forGlyphRange glyphRange: NSRange, in container: NSTextContainer)

Get the character index before trimming: Use NSLayoutManager.characterIndexForGlyph(at glyphIndex: Int)

Replace text which should be trimmed with "...Read More": UITextStorage.replaceCharacters(in range: NSRange, with attrString: NSAttributedString)

Title: Read/see More at the end of the label

Body:
I am trying to create a read more button at the end of my label. I want it to display 3 lines by default. I am coding in swift not objective c. Only when the user clicks the read more part of the label, should the label expand. It should look and work exactly like it does on instagram except on Instagram, it is in a tableview cell. My label and read more button will be in a scrollview. I have managed to get the expanding and contracting part working by adjusting the number of lines property of the label.

if descriptionLabel.numberOfLines == 0{
    descriptionLabel.numberOfLines = 3
}else {
    descriptionLabel.numberOfLines = 0
}
descriptionLabel.lineBreakMode = NSLineBreakMode.byWordWrapping

I am having problems with putting a "...more" at the end of the label and cutting the text off at the right place. I have looked at other people's responses to similar questions but nothing seems to work properly.

I can put a button over the last line of text so making the see more part of the label clickable also isn't the problem. The problem I am having is truncating the text at the right place and placing the see more text at the right place so that it displays.

I also want the read more button to only appear when it is necessary. I don't want to it appear when there are only 1-3 lines of text. This is also something I am having issues with.

I can't use this https://github.com/apploft/ExpandableLabel because it does not support scrollviews just tableviews.

the swift solution here didn't work: Add "...Read More" to the end of UILabel. It crashed the app.

Finally, the read more button should be in line with the last line of text and at the end of it. It would be an added benefit it this worked in a tableview cell as well!

Body:
I found ReadMoreTextView in Github, which is based on UITextView. The key method in this library is the following:

private func characterIndexBeforeTrim(range rangeThatFits: NSRange) -> Int {
    if let text = attributedReadMoreText {
        let readMoreBoundingRect = attributedReadMoreText(text: text, boundingRectThatFits: textContainer.size)
        let lastCharacterRect = layoutManager.boundingRectForCharacterRange(range: NSMakeRange(NSMaxRange(rangeThatFits)-1, 1), inTextContainer: textContainer)
        var point = lastCharacterRect.origin
        point.x = textContainer.size.width - ceil(readMoreBoundingRect.size.width)
        let glyphIndex = layoutManager.glyphIndex(for: point, in: textContainer, fractionOfDistanceThroughGlyph: nil)
        let characterIndex = layoutManager.characterIndexForGlyph(at: glyphIndex)
        return characterIndex - 1
    } else {
        return NSMaxRange(rangeThatFits) - readMoreText!.length
    }
}

To display text like "xxxx...Read More", the library

Get how many characters could be display in the UITextView: Use NSLayoutManager.characterRange(forGlyphRange:, actualGlyphRange:)

Get the position of the last visible character and the width of "...Read More": Use NSLayoutManager.boundingRect(forGlyphRange glyphRange: NSRange, in container: NSTextContainer)

Get the character index before trimming: Use NSLayoutManager.characterIndexForGlyph(at glyphIndex: Int)

Replace text which should be trimmed with "...Read More": UITextStorage.replaceCharacters(in range: NSRange, with attrString: NSAttributedString)


问:
What other RDBMS should my open source Java persistence library support
I'm releasing a new version of jOOQ, a Java persistence library built on top of JDBC. Currently, I support these seven RDBMS:

Oracle

MySQL

Postgres

H2

HSQLDB

DB2

SQLite (experimental)

With jOOQ I want to provide both broad and robust RDBMS support. This means I have to be quite selective in order to provide robustness with my integration tests. At the same time, I have to meet end user needs supporting important databases. I expect my end users to heavily rely on their databases. jOOQ is not an OR-mapper. Au contraire, jOOQ embraces vendor-specific features such as stored procedures, so the underlying database really matters to me.

In the next release, I want to add more RDBMS support. For example:

MS SQL

Derby

What would you suggest, and why? Please explain based on objective grounds and cite your references.

UPDATE:

The following RDBMS are now supported. Thanks again for feedback

CUBRID

Derby

Ingres

SQL Server

Sybase (both SQL Anywhere and ASE)

答:
With Ring Bearer's suggestion of sybase, and your listing of MS SQL and Derby, the only big ones left are Ingres and Firebird.

IBM also has a second database, Informix, but I know absolutely nothing about it besides the name :)


问:
I need help making a random number generator as a lock in a simple game
Basically, I wanted to be able to make a code that would generate a random number and have the user try and guess that number by putting in an input. I thought it would work, but it just runs the else statement everytime even if I do guess the right number.</p>

```<code>import random
def main():
  values = [1, 2, 3, 5, 7, 10]
  a = random.choice(values)
  print (a) ##########To see what the number is#########
  b = input('Enter a number: ')
  if b == a:
    print('You have guessed the number!')
  else:
    print('Try again')
    main()
main()
</code>```

答:
A couple things.  One, you don't convert the result of input to int.  So, '7' will never equal 7 because of how programming works, unless you convert it using the int() function.   Second thing, I noticed that you are using recursion to solve this problem.  Unfortunately, in your implementation you seem to be redefining the number to guess.  I can't imagine this is your intent for a "lock guessing game".  So, I rewrote it without this pitfall:

If you don't need recursion:

```<code>import random

values = [1, 2, 3, 5, 7, 10]
number = random.choice(values)
print("The secret number is {}".format(number))
while True:
    guess = int(input('Enter a number: '))
    if guess == number:
        print('You have guessed the number!')
        break
    else:
        print('Try again')
</code>```

If you must use recursion:

```<code>import random
def main(a=None):
    if a == None:
        values = [1, 2, 3, 5, 7, 10]
        a = random.choice(values)
        print (a) ##########To see what the number is#########
    b = int(input('Enter a number: '))
    if b == a:
        print('You have guessed the number!')
    else:
        print('Try again')
        main(a)
main()
</code>```

Body:
Basically, I wanted to be able to make a code that would generate a random number and have the user try and guess that number by putting in an input. I thought it would work, but it just runs the else statement everytime even if I do guess the right number.

import random
def main():
  values = [1, 2, 3, 5, 7, 10]
  a = random.choice(values)
  print (a) ##########To see what the number is#########
  b = input('Enter a number: ')
  if b == a:
    print('You have guessed the number!')
  else:
    print('Try again')
    main()
main()

Body:
A couple things.  One, you don't convert the result of input to int.  So, '7' will never equal 7 because of how programming works, unless you convert it using the int() function.   Second thing, I noticed that you are using recursion to solve this problem.  Unfortunately, in your implementation you seem to be redefining the number to guess.  I can't imagine this is your intent for a "lock guessing game".  So, I rewrote it without this pitfall:

If you don't need recursion:

import random

values = [1, 2, 3, 5, 7, 10]
number = random.choice(values)
print("The secret number is {}".format(number))
while True:
    guess = int(input('Enter a number: '))
    if guess == number:
        print('You have guessed the number!')
        break
    else:
        print('Try again')

If you must use recursion:

import random
def main(a=None):
    if a == None:
        values = [1, 2, 3, 5, 7, 10]
        a = random.choice(values)
        print (a) ##########To see what the number is#########
    b = int(input('Enter a number: '))
    if b == a:
        print('You have guessed the number!')
    else:
        print('Try again')
        main(a)
main()


问:
Cosmos DB Data Source - How to configure the Key in Azure Analysis Services
In Visual Studio I've created a Tabular Model that has a Cosmos DB Data Source.

If in Visual Studio I process the model the Data Source connects to Cosmos DB and I can browse the data in Excel.
I have successfully deployed the model to Azure Analysis Services, but quite correctly the deployment did not deploy the Cosmos DB Key, making my database effectively inaccessible.

I have tried:

Within Azure add the key to the Data Source.  There is nowhere in the Azure UI to do this.

From SSMS edit the Data Source.  You are prompted to enter the Cosmos DB Key, but SSMS throws an exception.

From SSMS execute an XMLA command to add the Cosmos DB Key to the Data Source, I've trawled MSDN for the property that needs to be set but cannot find what I need.

How do I deploy the key to the database so that Azure can use it?

答:
I am unable to repro your issue.

I am able to create Tabular Model that has a Cosmos DB Data Source in visual studio. It just give below warning which adding CosmosDB as data source. However, it still add the data source.

I am able to deploy model to Azure Analysis Service with cosmosDB key.

I am able to connect to Analysis service in SSMS and able to refresh CosmosDB Key without any issue.

what exception you see when using you edit data source and enters Cosmos DB key using SSMS?


问:
How to persist ViewState for reuse later?
Is it possible to save ViewState information, e.g. to session, so that when you navigate away from the page it is persisted somehow? Then when you return to that page you can reload the view state and the choices you've made are preserved.

Background

I have two pages, a report page, where you can pick data, do some filtering and sorting etc. and a chart-page, where the data you picked from the report page can be presented in different ways, with different choices for presentation.

If the user has tested different presentations, simply using the back-button could mean quite a few clicks before the user's back at the report page. I'd like a direct link to the report page.

Using QueryString to save control states is not an option.

I can't customize the ViewState storage for the whole application.

答:
Your link could automatically navigate back the required number of pages using JavaScript. Look at window.history, if you can count the number of pages forward you can navigate back that many.

The ViewState is already designed to persist the state of the user controls. If your user has made a selection and that selection is processed server side with a full page postback the new state of the controls will be saved in the ViewState (hidden input __VIEWSTATE).

If your report is using AJAX and partial page postbacks then you won't get the ViewState on the page anyway.

OwnerDisplayName: chriscena

LastEditorDisplayName: chriscena

OwnerDisplayName: Dave Anderson


问:
What to do, Learn while Developing the app or Learn first and then develop the app
I am planning to develop a web and mobile application. Have a look on this Question on OnStartups

I have some PHP & MySql knowledge, however I didn't do any major projects so far.

My skills on a scale of 5

PHP&MySql 3/5,

Javascript 3/5

CSS 3/5

Android 1.5/5

IPhone    0/5

web development (2/5)

web    design(2/5)

Software Development &    management
(1.5/5)

My app, as said in one of the answers
in the question, is not much complex
as Mint. If the complexity of Mint is
rated 8. My app would be 5/8

I have lot of interest in programming. Only thing bothering and bogging me is the time to make the app live. I don't understand how to estimate the time as I am not so experienced.

Should I start developing the app and learn all the concepts on the way?

or

should I wait learn programming completely first and then develop the app.?

Edit: A small Edit based on below answers. How should I test myself to know whether I have the minimum web development knowledge to start developing the application.

答:
As ckuetbach said you cannot really "learn programming completely" first. Because of the distinction practical/theoretical you must really learn-by-doing.

Here is what I would do:

1). Clearly define the apps functionality (first version functionality that is).

2). Try to understand what you can reuse in both the browser and the mobile applications (so as not to program the same thing twice). Example would be to keep the business logic on the server and access it via REST or something from the mobile app instead of programming it in there as well (if you want to make applications for both iPhone and Android phones you would have to develop the business logic once in ObjectiveC and once in Java). Obvious disadvantage is that the apps cannot think unless the phones are online (but I cannot judge that since I don't know exactly what you are doing).

3). Start coding (and learn while doing so, your best friend here is google, because it allows you to learn from how others who have done it before). Work in modules (and after the completion of a module jump to point 4).

4). Test (and test and test and test).

5). Iterate points 3 + 4 until you are satisfied for a first version (I say this because it is important do define the functionality you want in a first version; there is a clear relation between the amount of functionality and the amount of time it will take you to actually release the app).

6). Finally release the first version (and then start again from point 1, building on v1 to make v2).

** And like codie said: using an MVC framework is good for learning because it forces you (mostly) to program intelligently...plus the framework code is probably going to be better than what you would be able to do (or I for that matter).


问:
NodeList Data is not getting removed
I have an array object which has 3 objects. I want to remove all the objects except the first one.

Here is my data which I got from XML:

```<code>mrArr[0] = <Data>
                <G> "Val" = "5" </G>
           </Data>
mrArr[1] = <Data>
                <G> "Val" = "6" </G>
           </Data>
mrArr[2] = <Data>
                <G> "Val" = "7" </G>
           </Data>
</code>```

I have created a loop to try and do this but it is only removing one element. What is wrong with my loop?:

```<code>for(var i = 1; i < myArr.length; i++){
    myArr[i].remove();
}
</code>```

It is removing only one element.

答:
Since you're mutating the array after every iteration, array.length keeps decreasing. Hence, in your example, the loop gets executed only once, thereby removing only one element.

Here's a working example of what you're trying to achieve.

var nodes = document.getElementsByTagName('div');

console.log('Before removal:', nodes);

while (nodes.length > 1) {
  var node = nodes[nodes.length - 1];
  node.parentNode.removeChild(node);
}

console.log('After removal:', nodes);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="div-01">Here is div-01</div>
<div id="div-02">Here is div-02</div>
<div id="div-03">Here is div-03</div></code>```

Title: NodeList Data is not getting removed

Body:
I have an array object which has 3 objects. I want to remove all the objects except the first one.

Here is my data which I got from XML:

mrArr[0] = <Data>
                <G> "Val" = "5" </G>
           </Data>
mrArr[1] = <Data>
                <G> "Val" = "6" </G>
           </Data>
mrArr[2] = <Data>
                <G> "Val" = "7" </G>
           </Data>

I have created a loop to try and do this but it is only removing one element. What is wrong with my loop?:

for(var i = 1; i < myArr.length; i++){
    myArr[i].remove();
}

It is removing only one element.

Body:
Since you're mutating the array after every iteration, array.length keeps decreasing. Hence, in your example, the loop gets executed only once, thereby removing only one element.

Here's a working example of what you're trying to achieve.

var nodes = document.getElementsByTagName('div');

console.log('Before removal:', nodes);

while (nodes.length > 1) {
  var node = nodes[nodes.length - 1];
  node.parentNode.removeChild(node);
}

console.log('After removal:', nodes);

<div id="div-01">Here is div-01</div>
<div id="div-02">Here is div-02</div>
<div id="div-03">Here is div-03</div>


问:
Concatenate in SQL Server 2008 R2 failing when the monthid is 2 digits
I have a table like and server is SQL Server 2008 R2 where we cannot use concat function

```<code>YearID  |   MonthId
--------+----------
2017    |    1
2014    |    5
2014    |   10
2016    |   12
</code>```

I want to have the output as

```<code>201701
201405
201410
201612
</code>```

What I tried so far

```<code>select
    cast(YearId as varchar(50)) + '0' + cast(MonthId as varchar(50))
from
    TEST
</code>```

I am getting the output as

```<code>201701
201405
2014010
2016012
</code>```

When the monthID is 2 digits, it is failing.

How to tackle this situation?

答:
First you could verify the length of MonthId by LEN() function with simple case expression

```<code>SELECT CAST(YearID AS VARCHAR(8))+CASE
                                        WHEN LEN(CAST(MonthId AS VARCHAR(8))) = 2
                                        THEN CAST(MonthId AS VARCHAR(8))
                                        ELSE '0'+CAST(MonthId AS VARCHAR(8))
                                    END
FROM <table_name>;
</code>```

Result :

```<code>201701
201405
201410
201612
</code>```

Body:
I have a table like and server is SQL Server 2008 R2 where we cannot use concat function

YearID  |   MonthId
--------+----------
2017    |    1
2014    |    5
2014    |   10
2016    |   12

I want to have the output as

201701
201405
201410
201612

What I tried so far

select
    cast(YearId as varchar(50)) + '0' + cast(MonthId as varchar(50))
from
    TEST

I am getting the output as

201701
201405
2014010
2016012

When the monthID is 2 digits, it is failing.

How to tackle this situation?

Body:
First you could verify the length of MonthId by LEN() function with simple case expression

SELECT CAST(YearID AS VARCHAR(8))+CASE
                                        WHEN LEN(CAST(MonthId AS VARCHAR(8))) = 2
                                        THEN CAST(MonthId AS VARCHAR(8))
                                        ELSE '0'+CAST(MonthId AS VARCHAR(8))
                                    END
FROM <table_name>;

Result :

201701
201405
201410
201612


问:
Javascript: Avoiding multiple pop up boxes / check if div is empty
I created a pop up box that appears when a user clicks a button. Currently I am able to get the box to appear but when the user closes it and re-opens it the code is ran through again and another box is stacked on top of the old one.

What I want to do is make it so no matter how many times the user clicks the box it only shows one box... my thoughts was maybe checking if it was empty similar to How do I check if an HTML element is empty using jQuery? however that has not worked so far.

Any suggestions for a noob idiot? Appreciation for all responses in advance.

```<code><button onclick="popup()">text</button>

<script>
var box = document.getElementById('popupbox');

function popup(){
  box.style.display = "block";
  var content = document.createElement('div');
  content.className = 'boxstyle';
  content.innerHTML = ' ...a handful of tags...';
  box.appendChild(content);}

function exit(){
box.style.display = "none";}
</script>
</code>```

答:
You can create a popup using a modal as follows. I just copied code from here

<!DOCTYPE html>

Modal Example

<button id="myBtn">Open Modal</button>

    ×

Some text in the Modal..

```

Body:
I created a pop up box that appears when a user clicks a button. Currently I am able to get the box to appear but when the user closes it and re-opens it the code is ran through again and another box is stacked on top of the old one.

What I want to do is make it so no matter how many times the user clicks the box it only shows one box... my thoughts was maybe checking if it was empty similar to How do I check if an HTML element is empty using jQuery? however that has not worked so far.

Any suggestions for a noob idiot? Appreciation for all responses in advance.

<button onclick="popup()">text</button>

Body:
You can create a popup using a modal as follows. I just copied code from here

<!DOCTYPE html>
<html>
<head>
<style>
/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
    background-color: #fefefe;
    margin: auto;
    padding: 20px;
    border: 1px solid #888;
    width: 80%;
}

/* The Close Button */
.close {
    color: #aaaaaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: #000;
    text-decoration: none;
    cursor: pointer;
}
</style>
</head>
<body>

<h2>Modal Example</h2>

<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>

<!-- The Modal -->
<div id="myModal" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">&times;</span>
    <p>Some text in the Modal..</p>
  </div>

</div>

<script>
// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
btn.onclick = function() {
    modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}
</script>

</body>
</html>


问:
Is persistence.xml requied when working with Spring and Hibernate?
I am using a project with Spring JPA and Hibernate. Most of the things in persistence.xml can be specified in Spring applicationContext.xml file.

So is the persistence.xml required anymore?

Thanks.

答: persistence.xml is needed when you're using Hibernate through JPA, even though you're using Spring JPA. If you're using Hibernate directly, then persistence.xml isn't needed.


问:
Security Concerns About Building A Website
I am new in coding family ,so i am worry bit about things a coder should keep in mind as security concerns, so i come here hoping someone will help me.
i have learned all things which are necessary for building a website (Html,css,js,jquery,php,mysql).i know some basic tricks thanks to w3schools. but i need someone who can share his/her knowledge and practical experience, because i am really concern about security side.
i don,t want any security codes just things i should keep in mind.
Thanks in advance. </p>

答:
Some security issues, you have to prevent these areas (take care of these areas)

SQL Injections

Cross Site Scripting (XSS)

Broken Authentication & Session Management

Insecure Direct Object References

Cross-Site Request Forgery (CSRF)

Keep software up to date

Server side validation/form validation

File uploads

Email Form Header Injection

Malicious File Upload and Execution


问:
How to set listview in a add() order?
How to set listview in a add() order ?
Firstly this is code (not real code)

API_Interface.java

```<code>public interface API_Interface{
    @GET("/api/{buzz}")
    Call<Buzz> Buzz_API(@Path("buzz") String buzz);
}
</code>```

Buzz.java

```<code>public class Buzz{
    @SerializedName("buzz")
    @Expose
    private String buzz;

    public String getBuzz() {
        return buzz;
    }

    public void setBuzz(String buzz) {
        this.buzz = buzz;
    }
}
</code>```

MainActivity.class

```<code>@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_main);

        ListView listView = (ListView) findViewById(R.id.list_view);
        BuzzArrayList<Buzz> buzzArrayList = new BuzzArrayList<Buzz>();
        BuzzAdapter buzzAdapter = new BuzzAdapter(this, 0, buzzArrayList);
        listView.setAdapter(buzzAdapter);

        Retrofit buzz_retro = new Retrofit.Builder()
            .baseUrl("https://buzz.com")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

        API_Interface buzz_service = buzz_retro.create(API_Interface.class);

        //Get data
        Call<Buzz> buzz1 = buzz_service.buzz_API("Apple");
        buzz1.enqueue(new Callback<Buzz>() {
        @Override
        public void onResponse(Call<Buzz> call, Response<Buzz> response) {
            String buzz_1 = response.body().getBuzz();    //buzz_1="Apple"
            buzzArrayList.add(new Exchange(buzz_1));
            buzzAdapter.notifyDataSetChanged();
            }
        });

        Call<Buzz> buzz2 = buzz_service.buzz_API("Banana");
        buzz2.enqueue(new Callback<Buzz>() {
        @Override
        public void onResponse(Call<Buzz> call, Response<Buzz> response) {
            String buzz_2 = response.body().getBuzz();    //buzz_2="Banana"
            buzzArrayList.add(new Exchange(buzz_2));
            buzzAdapter.notifyDataSetChanged();
            }
        });

        Call<Buzz> buzz3 = buzz_service.buzz_API("Rice");
        buzz3.enqueue(new Callback<Buzz>() {
        @Override
        public void onResponse(Call<Buzz> call, Response<Buzz> response) {
            String buzz_3 = response.body().getBuzz();   //buzz_3="Rice"
            buzzArrayList.add(new Exchange(buzz_3));
            buzzAdapter.notifyDataSetChanged();
            }
        });
    }
</code>```

I just thought that listview displays in a add() order like this.

```<code>Apple
Banana
Rice
</code>```

However, in fact, listview displayed like this.

```<code>Banana
Rice
Apple
</code>```

or

```<code>Rice
Banana
Apple
</code>```

How do I change my code to display as intended ? I look forward to your response. Thank you.

答:
Call API synchronously. better to create a function for one API.call concurrently that function</p>

```<code>    Call<Buzz> buzz1 = buzz_service.buzz_API("Apple");
    buzz1.enqueue(new Callback<Buzz>() {
    @Override
    public void onResponse(Call<Buzz> call, Response<Buzz> response) {
        String buzz_1 = response.body().getBuzz();    //buzz_1="Apple"
        buzzArrayList.add(new Exchange(buzz_1));
        buzzAdapter.notifyDataSetChanged();

        Call<Buzz> buzz2 = buzz_service.buzz_API("Banana");
        buzz2.enqueue(new Callback<Buzz>() {
        @Override
        public void onResponse(Call<Buzz> call, Response<Buzz> response) {
            String buzz_2 = response.body().getBuzz();    //buzz_2="Banana"
            buzzArrayList.add(new Exchange(buzz_2));
            buzzAdapter.notifyDataSetChanged();

            Call<Buzz> buzz2 = buzz_service.buzz_API("Rice");
            buzz2.enqueue(new Callback<Buzz>() {
            @Override
            public void onResponse(Call<Buzz> call, Response<Buzz> response) {
                String buzz_3 = response.body().getBuzz();    //buzz_3="Rice"
                buzzArrayList.add(new Exchange(buzz_3));
                buzzAdapter.notifyDataSetChanged();
           }});
        }});
    }});
</code>```

Title: How to set listview in a add() order?

Body:
How to set listview in a add() order ?
Firstly this is code (not real code)

API_Interface.java

public interface API_Interface{
    @GET("/api/{buzz}")
    Call<Buzz> Buzz_API(@Path("buzz") String buzz);
}

Buzz.java

public class Buzz{
    @SerializedName("buzz")
    @Expose
    private String buzz;

    public String getBuzz() {
        return buzz;
    }

    public void setBuzz(String buzz) {
        this.buzz = buzz;
    }
}

MainActivity.class

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list_main);

        ListView listView = (ListView) findViewById(R.id.list_view);
        BuzzArrayList<Buzz> buzzArrayList = new BuzzArrayList<Buzz>();
        BuzzAdapter buzzAdapter = new BuzzAdapter(this, 0, buzzArrayList);
        listView.setAdapter(buzzAdapter);

        Retrofit buzz_retro = new Retrofit.Builder()
            .baseUrl("https://buzz.com")
            .addConverterFactory(GsonConverterFactory.create())
            .build();

        API_Interface buzz_service = buzz_retro.create(API_Interface.class);

        //Get data
        Call<Buzz> buzz1 = buzz_service.buzz_API("Apple");
        buzz1.enqueue(new Callback<Buzz>() {
        @Override
        public void onResponse(Call<Buzz> call, Response<Buzz> response) {
            String buzz_1 = response.body().getBuzz();    //buzz_1="Apple"
            buzzArrayList.add(new Exchange(buzz_1));
            buzzAdapter.notifyDataSetChanged();
            }
        });

        Call<Buzz> buzz2 = buzz_service.buzz_API("Banana");
        buzz2.enqueue(new Callback<Buzz>() {
        @Override
        public void onResponse(Call<Buzz> call, Response<Buzz> response) {
            String buzz_2 = response.body().getBuzz();    //buzz_2="Banana"
            buzzArrayList.add(new Exchange(buzz_2));
            buzzAdapter.notifyDataSetChanged();
            }
        });

        Call<Buzz> buzz3 = buzz_service.buzz_API("Rice");
        buzz3.enqueue(new Callback<Buzz>() {
        @Override
        public void onResponse(Call<Buzz> call, Response<Buzz> response) {
            String buzz_3 = response.body().getBuzz();   //buzz_3="Rice"
            buzzArrayList.add(new Exchange(buzz_3));
            buzzAdapter.notifyDataSetChanged();
            }
        });
    }

I just thought that listview displays in a add() order like this.

Apple
Banana
Rice

However, in fact, listview displayed like this.

Banana
Rice
Apple

or

Rice
Banana
Apple

How do I change my code to display as intended ? I look forward to your response. Thank you.

Body:
Call API synchronously. better to create a function for one API.call concurrently that function

    Call<Buzz> buzz1 = buzz_service.buzz_API("Apple");
    buzz1.enqueue(new Callback<Buzz>() {
    @Override
    public void onResponse(Call<Buzz> call, Response<Buzz> response) {
        String buzz_1 = response.body().getBuzz();    //buzz_1="Apple"
        buzzArrayList.add(new Exchange(buzz_1));
        buzzAdapter.notifyDataSetChanged();

        Call<Buzz> buzz2 = buzz_service.buzz_API("Banana");
        buzz2.enqueue(new Callback<Buzz>() {
        @Override
        public void onResponse(Call<Buzz> call, Response<Buzz> response) {
            String buzz_2 = response.body().getBuzz();    //buzz_2="Banana"
            buzzArrayList.add(new Exchange(buzz_2));
            buzzAdapter.notifyDataSetChanged();

            Call<Buzz> buzz2 = buzz_service.buzz_API("Rice");
            buzz2.enqueue(new Callback<Buzz>() {
            @Override
            public void onResponse(Call<Buzz> call, Response<Buzz> response) {
                String buzz_3 = response.body().getBuzz();    //buzz_3="Rice"
                buzzArrayList.add(new Exchange(buzz_3));
                buzzAdapter.notifyDataSetChanged();
           }});
        }});
    }});