问:
Angular/C# null body sent for POST
I've trying to do a POST in Angular, which makes a call to my C# backend. One API call works fine, but the other one doesn't exactly. I'm having a hard time figuring out what's going on, but I see that when I open the Network window in my browser's DevTools, the request payload has the JSON populated just fine. But in C#/the backend, it receives a null object, and I get a 200 code/null response from the call.

I've got the following code in Angular:

item.service.ts

```<code>private readonly _api = '...'
private postOptions = { headers: { 'Content-Type': 'application/json; charset=utf-8' }};

public addItem(formGroup: formGroup, isInactive: boolean): Observable<Item> {
    let api = ``;

    // These require different API calls depending on the flag
    if (isInactive)
        api = `${this._api}/AddInactiveItem`;
    else
        api = `${this._api}/AddItem`; // This one is the one having issues
    const body = ItemPost.parse(formGroup.value);

    return this.http.post<Item>(api, body, this.postOptions).pipe(
        this.handle(
            "POST successful",
            "Error with POST"
        )
    );
}
</code>```

item-post.ts

```<code>export class ItemPost {
    Name: string;
    Inactive: string;
    ...

    public static parse(obj: any): ItemPost {
        return !obj ? undefined : {
            Name: obj.name,
            Inactive: obj.inactive,
            ...
        };
    }
}
</code>```

My backend/POST code is in C#. Both of my POST methods are built the exact same, but with different SQL calls.

```<code>[HttpPost]
public JsonResult AddInactiveItem([FromBody] ItemBody item)
{
    if (!ModelState.IsValid)
        return Json(null);

    // Do SQL call for POST here, return JSON
}

[HttpPost]
public JsonResult AddItem([FromBody] ItemBody item) // This is where I have a breakpoint and it's passing in null
{
    if (!ModelState.IsValid)
        return Json(null);  // And this is where I find myself

    // Do SQL call for POST here, return JSON
}
</code>```

JSON Payload (sorry, unable to get a screenshot but this is what I'm seeing):

```<code>{"Name":"Test", ..., "Inactive":"N"}
</code>```

答:
I figured it out...and I feel dumb. Really dumb.

An int variable in Item was considered an optional int/number in the front-end for when an Item was considered active (not inactive), but in the backend, ItemBody didn't reflect that and was considered as just an int instead of int?. I had to dig through my ModelState errors through the debugger and it hinted this, but it's late at night and my mind didn't process it.

Gotta make sure all of the variable types are reflected properly in the Body object.

Title: Angular/C# null body sent for POST

Body:
I've trying to do a POST in Angular, which makes a call to my C# backend. One API call works fine, but the other one doesn't exactly. I'm having a hard time figuring out what's going on, but I see that when I open the Network window in my browser's DevTools, the request payload has the JSON populated just fine. But in C#/the backend, it receives a null object, and I get a 200 code/null response from the call.

I've got the following code in Angular:

item.service.ts

private readonly _api = '...'
private postOptions = { headers: { 'Content-Type': 'application/json; charset=utf-8' }};

public addItem(formGroup: formGroup, isInactive: boolean): Observable<Item> {
    let api = ``;

    // These require different API calls depending on the flag
    if (isInactive)
        api = `${this._api}/AddInactiveItem`;
    else
        api = `${this._api}/AddItem`; // This one is the one having issues
    const body = ItemPost.parse(formGroup.value);

    return this.http.post<Item>(api, body, this.postOptions).pipe(
        this.handle(
            "POST successful",
            "Error with POST"
        )
    );
}

item-post.ts

export class ItemPost {
    Name: string;
    Inactive: string;
    ...

    public static parse(obj: any): ItemPost {
        return !obj ? undefined : {
            Name: obj.name,
            Inactive: obj.inactive,
            ...
        };
    }
}

My backend/POST code is in C#. Both of my POST methods are built the exact same, but with different SQL calls.

[HttpPost]
public JsonResult AddInactiveItem([FromBody] ItemBody item)
{
    if (!ModelState.IsValid)
        return Json(null);

    // Do SQL call for POST here, return JSON
}

[HttpPost]
public JsonResult AddItem([FromBody] ItemBody item) // This is where I have a breakpoint and it's passing in null
{
    if (!ModelState.IsValid)
        return Json(null);  // And this is where I find myself

    // Do SQL call for POST here, return JSON
}

JSON Payload (sorry, unable to get a screenshot but this is what I'm seeing):

{"Name":"Test", ..., "Inactive":"N"}


来源: stackexchange

问:
asp.net Button OnClick event not firing
I have problem in asp.net button control.

I define a button in form, onclick event of button is not firing when I click on the button.

```<code><asp:Button ID="btn_QuaSave" runat="server" Text="SAVE" OnClick="btn_QuaSave_Click" />

protected void btn_QuaSave_Click(object sender, EventArgs e)
{

}
</code>```

答: Even i had two forms one for desktop view and other for mobile view , Removed one formed worked for me . I dint knew asp.page should have only one form.</p>

ContentLicense: CC BY-SA 3.0

Title: asp.net Button OnClick event not firing

Body:
I have problem in asp.net button control.

I define a button in form, onclick event of button is not firing when I click on the button.

<asp:Button ID="btn_QuaSave" runat="server" Text="SAVE" OnClick="btn_QuaSave_Click" />

protected void btn_QuaSave_Click(object sender, EventArgs e)
{

}

ContentLicense: CC BY-SA 4.0


问:
Getting "System.InvalidOperationException: 'ExecuteNonQuery: Connection property has not been initialized.'"
I am working on a SQL connection through C# but on the sqlCmd.ExecuteNonQuery(); line, when I run it and put information into the form it does not work. Crashing and giving me the error, the code for my program follows. Also include a screenshot of the form. I have been trying to fix this for a while but no luck, tried switching the code around and more but generally just didn't work.
https://i.stack.imgur.com/rpFGj.png

```<code>using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormApp32
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        string connectionString = "Data Source=DESKTOP-SQ1V840;Initial Catalog=UserRegistration;Integrated Security=True";

        private void Form2_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            using (SqlConnection sqlCon = new SqlConnection(connectionString))
            {
                if (textBox5.Text + textBox6.Text == " ")
                    MessageBox.Show("Please fill mandatory fields");

                sqlCon.Open();
                SqlCommand sqlCmd = new SqlCommand("UserAdd");
                sqlCmd.CommandType = CommandType.StoredProcedure;
                sqlCmd.Parameters.AddWithValue("@First_Name", textBox1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Last_Name", textBox2.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Email_ID", textBox3.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Contact", textBox4.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Address", richTextBox1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Gender", radioButton1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Gender", radioButton2.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Department", comboBox1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Username", textBox5.Text.Trim());

                using (var connectionString = new SqlConnection("Data Source=DESKTOP-SQ1V840;Initial Catalog=UserRegistration;Integrated Security=True"))
                using (var cmd = new SqlDataAdapter())
                using (var insertCommand = new SqlCommand("INSERT INTO Application VALUES (@First_Name, @Last_Name, @Email_ID, @Contact, @Address, @Gender, @Department, @Username, @Password) "))
                {
                    insertCommand.Connection = connectionString;
                    cmd.InsertCommand = insertCommand;

                    connectionString.Open();

                }
                sqlCmd.ExecuteNonQuery();
                    MessageBox.Show("Registration successful");
                }
            }

        }
    }
</code>```

I've fixed it up a little but it's still giving me a error for "sqlCmd.Connection = connectionString;" giving me a error on the connectionString part

The code shows following now

```<code>                SqlCommand sqlCmd = new SqlCommand("UserAdd");
                sqlCmd.CommandType = CommandType.StoredProcedure;
                sqlCmd.Parameters.AddWithValue("@First_Name", textBox1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Last_Name", textBox2.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Email_ID", textBox3.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Contact", textBox4.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Address", richTextBox1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Gender", radioButton1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Gender", radioButton2.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Department", comboBox1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Username", textBox5.Text.Trim());
                sqlCmd.Connection = connectionString;```

```

答:
You add some code twice, it's redundant ...
So you have to do only this:</p>

```<code>string connectionString = "Data Source=DESKTOP-SQ1V840;Initial Catalog=UserRegistration;Integrated Security=True";

    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            using (SqlConnection sqlCon = new SqlConnection(connectionString))
            {
                if (textBox5.Text.Trim() + textBox6.Text.Trim() == "")
                 {
                     MessageBox.Show("Please fill mandatory fields");
                     return;
                 }

                sqlCon.Open();
                using (SqlCommand sqlCmd = new SqlCommand("UserAdd", sqlCon)) // you missed to pass connection to command
                {
                    sqlCmd.CommandType = CommandType.StoredProcedure;
                    sqlCmd.Parameters.AddWithValue("@First_Name", textBox1.Text.Trim());
                    sqlCmd.Parameters.AddWithValue("@Last_Name", textBox2.Text.Trim());
                    sqlCmd.Parameters.AddWithValue("@Email_ID", textBox3.Text.Trim());
                    sqlCmd.Parameters.AddWithValue("@Contact", textBox4.Text.Trim());
                    sqlCmd.Parameters.AddWithValue("@Address", richTextBox1.Text.Trim());
                    sqlCmd.Parameters.AddWithValue("@Gender", radioButton1.Text.Trim());
                    sqlCmd.Parameters.AddWithValue("@Department", comboBox1.Text.Trim()); // also I think here must be comboBox1.SelectedValue, not Text property
                    sqlCmd.Parameters.AddWithValue("@Username", textBox5.Text.Trim());

                    sqlCmd.ExecuteNonQuery();
                }
            }
            MessageBox.Show("Registration successful");
        }
        catch(Exception e)
        {
            MessageBox.Show($"Error on SQL \"UserAdd\" procedure: {e.Message}");
        }
    }
</code>```

Body:
I am working on a SQL connection through C# but on the sqlCmd.ExecuteNonQuery(); line, when I run it and put information into the form it does not work. Crashing and giving me the error, the code for my program follows. Also include a screenshot of the form. I have been trying to fix this for a while but no luck, tried switching the code around and more but generally just didn't work.
https://i.stack.imgur.com/rpFGj.png

using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormApp32
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }

        string connectionString = "Data Source=DESKTOP-SQ1V840;Initial Catalog=UserRegistration;Integrated Security=True";

        private void Form2_Load(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            using (SqlConnection sqlCon = new SqlConnection(connectionString))
            {
                if (textBox5.Text + textBox6.Text == " ")
                    MessageBox.Show("Please fill mandatory fields");

                sqlCon.Open();
                SqlCommand sqlCmd = new SqlCommand("UserAdd");
                sqlCmd.CommandType = CommandType.StoredProcedure;
                sqlCmd.Parameters.AddWithValue("@First_Name", textBox1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Last_Name", textBox2.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Email_ID", textBox3.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Contact", textBox4.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Address", richTextBox1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Gender", radioButton1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Gender", radioButton2.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Department", comboBox1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Username", textBox5.Text.Trim());

                using (var connectionString = new SqlConnection("Data Source=DESKTOP-SQ1V840;Initial Catalog=UserRegistration;Integrated Security=True"))
                using (var cmd = new SqlDataAdapter())
                using (var insertCommand = new SqlCommand("INSERT INTO Application VALUES (@First_Name, @Last_Name, @Email_ID, @Contact, @Address, @Gender, @Department, @Username, @Password) "))
                {
                    insertCommand.Connection = connectionString;
                    cmd.InsertCommand = insertCommand;

                    connectionString.Open();

                }
                sqlCmd.ExecuteNonQuery();
                    MessageBox.Show("Registration successful");
                }
            }

        }
    }

I've fixed it up a little but it's still giving me a error for "sqlCmd.Connection = connectionString;" giving me a error on the connectionString part

The code shows following now

                SqlCommand sqlCmd = new SqlCommand("UserAdd");
                sqlCmd.CommandType = CommandType.StoredProcedure;
                sqlCmd.Parameters.AddWithValue("@First_Name", textBox1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Last_Name", textBox2.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Email_ID", textBox3.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Contact", textBox4.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Address", richTextBox1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Gender", radioButton1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Gender", radioButton2.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Department", comboBox1.Text.Trim());
                sqlCmd.Parameters.AddWithValue("@Username", textBox5.Text.Trim());
                sqlCmd.Connection = connectionString;```

Body:
You add some code twice, it's redundant ...
So you have to do only this:

string connectionString = "Data Source=DESKTOP-SQ1V840;Initial Catalog=UserRegistration;Integrated Security=True";

    private void button1_Click(object sender, EventArgs e)
    {
        try
        {
            using (SqlConnection sqlCon = new SqlConnection(connectionString))
            {
                if (textBox5.Text.Trim() + textBox6.Text.Trim() == "")
                 {
                     MessageBox.Show("Please fill mandatory fields");
                     return;
                 }

                sqlCon.Open();
                using (SqlCommand sqlCmd = new SqlCommand("UserAdd", sqlCon)) // you missed to pass connection to command
                {
                    sqlCmd.CommandType = CommandType.StoredProcedure;
                    sqlCmd.Parameters.AddWithValue("@First_Name", textBox1.Text.Trim());
                    sqlCmd.Parameters.AddWithValue("@Last_Name", textBox2.Text.Trim());
                    sqlCmd.Parameters.AddWithValue("@Email_ID", textBox3.Text.Trim());
                    sqlCmd.Parameters.AddWithValue("@Contact", textBox4.Text.Trim());
                    sqlCmd.Parameters.AddWithValue("@Address", richTextBox1.Text.Trim());
                    sqlCmd.Parameters.AddWithValue("@Gender", radioButton1.Text.Trim());
                    sqlCmd.Parameters.AddWithValue("@Department", comboBox1.Text.Trim()); // also I think here must be comboBox1.SelectedValue, not Text property
                    sqlCmd.Parameters.AddWithValue("@Username", textBox5.Text.Trim());

                    sqlCmd.ExecuteNonQuery();
                }
            }
            MessageBox.Show("Registration successful");
        }
        catch(Exception e)
        {
            MessageBox.Show($"Error on SQL \"UserAdd\" procedure: {e.Message}");
        }
    }


问:
DraggableScrollableView and GoogleMaps - Maps showing as white blank page
I am trying to use DraggableScrollableSheet as a Scaffold bottomSheet, and a body with Google Maps, but no luck so far. Any tips what could be wrong?</p>

```<code>    return Scaffold(
        appBar: AppBar(
          title: Text("Meeting"),
          backgroundColor: Colors.black,
          automaticallyImplyLeading: false,
        ),
        body: Stack(
          children: <Widget>[
            GoogleMap(
              markers: Set<Marker>.of(markers.values),
              // YOUR MARKS IN MAP
              initialCameraPosition: CameraPosition(
                  target: LatLng(47.502941, 18.999161),
                  zoom: 1),
              myLocationEnabled: true,
              zoomControlsEnabled: true,

            ),
          ],
        ),
        bottomSheet:             DraggableScrollableSheet(
          initialChildSize: 0.3,
          minChildSize: 0.1,
          maxChildSize: 0.9,
          builder: (context, scrollController) {
            return SingleChildScrollView(
              child: Card(
                 Text("test"),
            );
          },
        ),
        ,
        bottomNavigationBar: BottomNavigationBar(
          backgroundColor: Colors.white,
          selectedItemColor: Colors.black,
          unselectedItemColor: Colors.black,
          iconSize: 26,
          items: const <BottomNavigationBarItem>[
            BottomNavigationBarItem(
              icon: Icon(Icons.close),
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.check),
            ),
          ],
        ));
  }
}
</code>```

答: I don't know exactly what is going wrong. But the way I've always used a draggable sheet is by putting it in a stack with the main view. You could try that. If the problem is related to google map then you could check the map api key is set properly or not. </p>

Body:
I am trying to use DraggableScrollableSheet as a Scaffold bottomSheet, and a body with Google Maps, but no luck so far. Any tips what could be wrong?

    return Scaffold(
        appBar: AppBar(
          title: Text("Meeting"),
          backgroundColor: Colors.black,
          automaticallyImplyLeading: false,
        ),
        body: Stack(
          children: <Widget>[
            GoogleMap(
              markers: Set<Marker>.of(markers.values),
              // YOUR MARKS IN MAP
              initialCameraPosition: CameraPosition(
                  target: LatLng(47.502941, 18.999161),
                  zoom: 1),
              myLocationEnabled: true,
              zoomControlsEnabled: true,

            ),
          ],
        ),
        bottomSheet:             DraggableScrollableSheet(
          initialChildSize: 0.3,
          minChildSize: 0.1,
          maxChildSize: 0.9,
          builder: (context, scrollController) {
            return SingleChildScrollView(
              child: Card(
                 Text("test"),
            );
          },
        ),
        ,
        bottomNavigationBar: BottomNavigationBar(
          backgroundColor: Colors.white,
          selectedItemColor: Colors.black,
          unselectedItemColor: Colors.black,
          iconSize: 26,
          items: const <BottomNavigationBarItem>[
            BottomNavigationBarItem(
              icon: Icon(Icons.close),
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.check),
            ),
          ],
        ));
  }
}


问:
Use of randomAccessFileOrArray()
can anyone explain me what is the use of randomAccessFileOrArray() function in iText and how it is diferent from using Files.readAllBytes().

I am using following line of code:

```<code>PdfReader reader = new PdfReader(Files.readAllBytes((new File(filenameSource)).toPath()));
</code>```

But at runtime, I met with java heap space error, so I found out the following option:

```<code>PdfReader reader = new PdfReader(new RandomAccessFileOrArray(filenameSource),null);
</code>```

But I am not quite sure what difference does this create. Can anyone help me out here please?

答:
As you use both the itext and the itext7 tag, it is unclear which iText version you use. Considering the code you quote, though, it cannot be iText version 7 as there a PdfReader does not accept a RandomAccessFileOrArray as constructor argument.

In iText 5, no matter which PdfReader constructor you use, eventually internally a RandomAccessSource implementation is used to access the pdf. This interface Represents an abstract source that bytes can be read from. The main data retrieval method in that interface is

```<code>public int get(long position, byte bytes[], int off, int len) throws IOException;
</code>```

making this essentially a generalized InputStream, adding the position parameter for random access.

RandomAccessFileOrArray actually merely wraps a RandomAccessSource and provides a number of methods for retrieving data in specific formats (readChar, readFloat, readLine, ...). When used in a PdfReader constructor, only that underlying RandomAccessSource is used.

If constructed for a file name, it generates a RAFRandomAccessSource based on a RandomAccessFile for the named file, just like

```<code>PdfReader reader = new PdfReader(filenameSource);
</code>```

would do.

An important difference, though: When using the RandomAccessFileOrArray based PdfReader constructor the PdfReader handles the PDF in partial mode, i.e. it only reads the parts it needs for the desired operations on the PDF and forgets them as soon as they are not needed anymore. Otherwise, the PDF is parsed completely and kept in memory the whole time.

A byte[] in a PdfReader constructor will be wrapped in an ArrayRandomAccessSource and loaded completely, not in partial mode.

The differences between the approaches are, therefore, which exact implementation of that interface is used to read the pdf bytes and whether or not partial mode is used (with an impact on memory use):

In case of

```<code>PdfReader reader = new PdfReader(Files.readAllBytes((new File(filenameSource)).toPath()));
</code>```

the pdf is first loaded into a byte[] in memory, an array that is as big as the original pdf, which then in turn is used by PdfReader to parse the whole PDF from.

Memory requirements: The size of the original PDF plus the size of the complete parsed PDF.

In case of

```<code>PdfReader reader = new PdfReader(filenameSource);
</code>```

PdfReader (via the RAFRandomAccessSource instance) immediately reads from the file on disk without a byte[] in-between and parses the whole PDF.

Memory requirements: The size of the complete parsed PDF.

In case of

```<code>PdfReader reader = new PdfReader(new RandomAccessFileOrArray(filenameSource),null);
</code>```

PdfReader (via the RAFRandomAccessSource instance) immediately reads from the file on disk without a byte[] in-between and parses only the parts of the PDF used in your processing.

Memory requirements: The size of the partially parsed PDF.

Thus, in case of large PDFs there is a substantial difference between the resource hunger of these three approaches.

Performance differences depend on your use case; if you manipulate large parts of your PDF, partial reading will be slower. If you only manipulate some details, partial reading will be faster. Furthermore, if you need to delete the file you read from quickly (while still processing it), a byte[] based solution is the approach of choice.

Thus, it makes sense to know all approaches and use them depending on the use case at hand.

Title: Use of randomAccessFileOrArray()

Body:
can anyone explain me what is the use of randomAccessFileOrArray() function in iText and how it is diferent from using Files.readAllBytes().

I am using following line of code:

PdfReader reader = new PdfReader(Files.readAllBytes((new File(filenameSource)).toPath()));

But at runtime, I met with java heap space error, so I found out the following option:

PdfReader reader = new PdfReader(new RandomAccessFileOrArray(filenameSource),null);

But I am not quite sure what difference does this create. Can anyone help me out here please?

Body:
As you use both the itext and the itext7 tag, it is unclear which iText version you use. Considering the code you quote, though, it cannot be iText version 7 as there a PdfReader does not accept a RandomAccessFileOrArray as constructor argument.

In iText 5, no matter which PdfReader constructor you use, eventually internally a RandomAccessSource implementation is used to access the pdf. This interface Represents an abstract source that bytes can be read from. The main data retrieval method in that interface is

public int get(long position, byte bytes[], int off, int len) throws IOException;

making this essentially a generalized InputStream, adding the position parameter for random access.

RandomAccessFileOrArray actually merely wraps a RandomAccessSource and provides a number of methods for retrieving data in specific formats (readChar, readFloat, readLine, ...). When used in a PdfReader constructor, only that underlying RandomAccessSource is used.

If constructed for a file name, it generates a RAFRandomAccessSource based on a RandomAccessFile for the named file, just like

PdfReader reader = new PdfReader(filenameSource);

would do.

An important difference, though: When using the RandomAccessFileOrArray based PdfReader constructor the PdfReader handles the PDF in partial mode, i.e. it only reads the parts it needs for the desired operations on the PDF and forgets them as soon as they are not needed anymore. Otherwise, the PDF is parsed completely and kept in memory the whole time.

A byte[] in a PdfReader constructor will be wrapped in an ArrayRandomAccessSource and loaded completely, not in partial mode.

The differences between the approaches are, therefore, which exact implementation of that interface is used to read the pdf bytes and whether or not partial mode is used (with an impact on memory use):

In case of

PdfReader reader = new PdfReader(Files.readAllBytes((new File(filenameSource)).toPath()));

the pdf is first loaded into a byte[] in memory, an array that is as big as the original pdf, which then in turn is used by PdfReader to parse the whole PDF from.

Memory requirements: The size of the original PDF plus the size of the complete parsed PDF.

In case of

PdfReader reader = new PdfReader(filenameSource);

PdfReader (via the RAFRandomAccessSource instance) immediately reads from the file on disk without a byte[] in-between and parses the whole PDF.

Memory requirements: The size of the complete parsed PDF.

In case of

PdfReader reader = new PdfReader(new RandomAccessFileOrArray(filenameSource),null);

PdfReader (via the RAFRandomAccessSource instance) immediately reads from the file on disk without a byte[] in-between and parses only the parts of the PDF used in your processing.

Memory requirements: The size of the partially parsed PDF.

Thus, in case of large PDFs there is a substantial difference between the resource hunger of these three approaches.

Performance differences depend on your use case; if you manipulate large parts of your PDF, partial reading will be slower. If you only manipulate some details, partial reading will be faster. Furthermore, if you need to delete the file you read from quickly (while still processing it), a byte[] based solution is the approach of choice.

Thus, it makes sense to know all approaches and use them depending on the use case at hand.


问:
How to calculate time taken for request to be served in rails?
I want to calculate the time taken by application to serve a particular request. i.e.. difference between the time the request comes to the server and time the server responded with response back

In c#, we have something called Global.ascx in which we have the functions like Application_BeginRequest and Application_EndRequest which can be used for this purpose.

Similarly does rails contains these types of functions where I can record the request timings?

答:
There is a module call Benchmark in ruby for this.

For example,

```<code>def your_action_to_measure
  time = Benchmark.measure do
    #Your code here
  end
  puts time # => This will print the time in server.
end
</code>```

Hope this helps!

Body:
There is a module call Benchmark in ruby for this.

For example,

def your_action_to_measure
  time = Benchmark.measure do
    #Your code here
  end
  puts time # => This will print the time in server.
end

Hope this helps!


问:
Open hyperlink in new tab and run a php function
I have a countdown timer in javascript and when it gets to the end I'd like to be able to display a hyperlink or button that opens the url in a new tab and at the same time call a php function (which would in turn update a piece of user metadata).

I am able to do one or the other but not both at the same time.

Below is everything I've tried so far.

Please can someone help?

FYI my site is a wordpress.org site and I have all the code below within the functions.php file.

This code will open the hyperlink in a new tab but will not call the function updateUserEndSession:

```<code>\\
\\ bla bla javascript countdown code...
\\
if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = '<a href="https://www.mywebsite.com/media/imagex.jpg" target="_blank">End</a>';

 }
        }, 1000);
        </script>

        </body>
        </html>

    <?php

}

if(isset($_POST['End_sesh'])){
        updateUserEndSession();
}

function updateUserEndSession(){
    $current_user_id = get_current_user_id();
    update_user_meta( $current_user_id, 'insessionbool', False );
}

</code>```

This code will call the function updateUserEndSession via a button click but will not open any hyperlink:

```<code>\\
\\ bla bla javascript countdown code...
\\
if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = '<form method="post" ><input type="submit" value="End" name="End_sesh"/></form>';

 }
        }, 1000);
        </script>

        </body>
        </html>

    <?php

}

if(isset($_POST['End_sesh'])){
        updateUserEndSession();
}

function updateUserEndSession(){
    $current_user_id = get_current_user_id();
    update_user_meta( $current_user_id, 'insessionbool', False );
}

</code>```

This code is my current best attempt to do both. It opens the hyperlink in a new tab but still does not call my function unfortunately:

```<code>\\
\\ bla bla javascript countdown code...
\\
if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = '<form method="post" action="https://www.mywebsite.com/media/imagex.jpg"  target="_blank"><input type="submit" value="End" name="End_sesh"/></form>';

 }
        }, 1000);
        </script>

        </body>
        </html>

    <?php

}

if(isset($_POST['End_sesh']))
    {
        updateUserEndSession();
    }

function updateUserEndSession(){
    $current_user_id = get_current_user_id();
    update_user_meta( $current_user_id, 'insessionbool', False );
}

</code>```

答:
Check what do you get in

```<code>print_r($_POST);
</code>```

Another options is to use GET

```<code>document.getElementById("demo").innerHTML = '<a href="https://www.mywebsite.com/?call=endUser" target="_blank">End</a>';
</code>```

and in PHP handle like this

```<code>if(isset($_GET['call']) && $_GET['call'] == 'endUser')
{
    updateUserEndSession();
}
</code>```

Body:
I have a countdown timer in javascript and when it gets to the end I'd like to be able to display a hyperlink or button that opens the url in a new tab and at the same time call a php function (which would in turn update a piece of user metadata).

I am able to do one or the other but not both at the same time.

Below is everything I've tried so far.

Please can someone help?

FYI my site is a wordpress.org site and I have all the code below within the functions.php file.

This code will open the hyperlink in a new tab but will not call the function updateUserEndSession:

\\
\\ bla bla javascript countdown code...
\\
if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = 'End';

 }
        }, 1000);
        </script>

    <?php

}

if(isset($_POST['End_sesh'])){
        updateUserEndSession();
}

function updateUserEndSession(){
    $current_user_id = get_current_user_id();
    update_user_meta( $current_user_id, 'insessionbool', False );
}

This code will call the function updateUserEndSession via a button click but will not open any hyperlink:

\\
\\ bla bla javascript countdown code...
\\
if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = '<form method="post" ><input type="submit" value="End" name="End_sesh"/></form>';

 }
        }, 1000);
        </script>

    <?php

}

if(isset($_POST['End_sesh'])){
        updateUserEndSession();
}

function updateUserEndSession(){
    $current_user_id = get_current_user_id();
    update_user_meta( $current_user_id, 'insessionbool', False );
}

This code is my current best attempt to do both. It opens the hyperlink in a new tab but still does not call my function unfortunately:

\\
\\ bla bla javascript countdown code...
\\
if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = '<form method="post" action="https://www.mywebsite.com/media/imagex.jpg"  target="_blank"><input type="submit" value="End" name="End_sesh"/></form>';

 }
        }, 1000);
        </script>

    <?php

}

if(isset($_POST['End_sesh']))
    {
        updateUserEndSession();
    }

function updateUserEndSession(){
    $current_user_id = get_current_user_id();
    update_user_meta( $current_user_id, 'insessionbool', False );
}

Body:
Check what do you get in

print_r($_POST);

Another options is to use GET

document.getElementById("demo").innerHTML = '<a href="https://www.mywebsite.com/?call=endUser" target="_blank">End</a>';

and in PHP handle like this

if(isset($_GET['call']) && $_GET['call'] == 'endUser')
{
    updateUserEndSession();
}


问:
How to turn txt file to nice dataframe
I have a txt file containing Track ID, Song ID, Artist Name and Song name. I'd like to convert it into a dataframe in R to do some analysis. What would be a good function to use to separate the data? Below is the top row of the dataset. Thanks!</p>

```<code>TRMMMKD128F425225D<SEP>SOVFVAK12A8C1350D9<SEP>Karkkiautomaatti<SEP>Tanssi vaan
</code>```

答:
We can use read.table to directly read the file as a dataframe but separator (sep) between columns can be of only one character.

So we can first use readLines to read the text file, replace '<SEP>' using gsub with a single character ('\t') and then use read.table specifying column names.

```<code>data <- read.table(text = gsub('<SEP>', '\t',
         readLines('filename.txt'), fixed = TRUE),
         col.names = c('TrackID', 'SongID', 'ArtistName', 'SongName'),sep = "\t")
data

#             TrackID             SongID       ArtistName    SongName
#1 TRMMMKD128F425225D SOVFVAK12A8C1350D9 Karkkiautomaatti Tanssi vaan
</code>```

Title: How to turn txt file to nice dataframe

Body:
I have a txt file containing Track ID, Song ID, Artist Name and Song name. I'd like to convert it into a dataframe in R to do some analysis. What would be a good function to use to separate the data? Below is the top row of the dataset. Thanks!

TRMMMKD128F425225D<SEP>SOVFVAK12A8C1350D9<SEP>Karkkiautomaatti<SEP>Tanssi vaan

Body:
We can use read.table to directly read the file as a dataframe but separator (sep) between columns can be of only one character.

So we can first use readLines to read the text file, replace '<SEP>' using gsub with a single character ('\t') and then use read.table specifying column names.

data <- read.table(text = gsub('<SEP>', '\t',
         readLines('filename.txt'), fixed = TRUE),
         col.names = c('TrackID', 'SongID', 'ArtistName', 'SongName'),sep = "\t")
data

#             TrackID             SongID       ArtistName    SongName
#1 TRMMMKD128F425225D SOVFVAK12A8C1350D9 Karkkiautomaatti Tanssi vaan


问:
CSS: Is there a way to apply inherited padding as negative margin?
Context

I'm using React and  must be clickable with <Link> of react-router-dom. Padding of  changes when I resize browser window because it uses css framework named Carbon. I have to <Link> =  tag to fit width/height of . It means that when I click , hyperlink has to work as expected.

Problem

It can bo solved by negative margin, and it should be same with padding. But, padding is dynamic. Therefore, I want to use inherited padding as negative margin.

     link

```

<pre class="lang-css prettyprint-override"><code>a {
  padding: inherit;
  margin: <negative of inherited padding>
}
</code>```

I cannot know padding of parent because it is dynamic. Actually, my real code is from https://react.carbondesignsystem.com/?path=/story/datatable--default which is framework I'm using.

How can I solve it?

答:
Use code as below

Here I wrote an example

```<code>import React, { Component } from "react";
import { render } from "react-dom";
import ReactDOM from "react-dom";
import "./style.css";

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      padding: 0
    };
  }

  componentDidMount() {
    const el = this.divElement;
    const style = window.getComputedStyle(el);
    const padding = style.getPropertyValue("padding").match(/\d+/);;
    this.setState({ padding });
  }

  render() {
    return (
      <table>
        <tr>
          <td>
            <a
              ref={divElement => {
                this.divElement = divElement;
              }}
              href="google.com"
              style={{margin: this.state.padding* -1 }}>
              link padding: <b>{this.state.padding}px</b>
            </a>
          </td>
        </tr>
      </table>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));
</code>```

Body:
Context

I'm using React and  must be clickable with <Link> of react-router-dom. Padding of  changes when I resize browser window because it uses css framework named Carbon. I have to <Link> =  tag to fit width/height of . It means that when I click , hyperlink has to work as expected.

Problem

It can bo solved by negative margin, and it should be same with padding. But, padding is dynamic. Therefore, I want to use inherited padding as negative margin.

     link

a {
  padding: inherit;
  margin: <negative of inherited padding>
}

I cannot know padding of parent because it is dynamic. Actually, my real code is from https://react.carbondesignsystem.com/?path=/story/datatable--default which is framework I'm using.

How can I solve it?

Body:
Use code as below

Here I wrote an example

import React, { Component } from "react";
import { render } from "react-dom";
import ReactDOM from "react-dom";
import "./style.css";

class App extends Component {
  constructor(props) {
    super(props);

    this.state = {
      padding: 0
    };
  }

  componentDidMount() {
    const el = this.divElement;
    const style = window.getComputedStyle(el);
    const padding = style.getPropertyValue("padding").match(/\d+/);;
    this.setState({ padding });
  }

  render() {
    return (
      <table>
        <tr>
          <td>
            <a
              ref={divElement => {
                this.divElement = divElement;
              }}
              href="google.com"
              style={{margin: this.state.padding* -1 }}>
              link padding: <b>{this.state.padding}px</b>
            </a>
          </td>
        </tr>
      </table>
    );
  }
}

ReactDOM.render(<App />, document.getElementById("root"));


问:
Android - Media Scanner not working on api 28-29
I'm scanning files using MediaScanner. But API 28 and 29 don't work.

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, file));
```

<p>I used <code>Broadcast</code>, but it didn't work the same way. Because it is "deprecated".</p>

```java public static class FilesScanner extends ContextWrapper implements MediaScannerConnection.MediaScannerConnectionClient{

        private MediaScannerConnection connection = null;
        private String SCAN_FILE_PATH = "";
        private String SCAN_FILE_MIME_TYPE = "*/*";

        public static FilesScanner with(Context context, String SCAN_FILE_PATH){ return new FilesScanner(context, SCAN_FILE_PATH, "*/*"); }
        public static FilesScanner with(Context context, String SCAN_FILE_PATH, String SCAN_FILE_MIME_TYPE){ return new FilesScanner(context, SCAN_FILE_PATH, SCAN_FILE_MIME_TYPE); }
        private FilesScanner(Context context, String SCAN_FILE_PATH, String SCAN_FILE_MIME_TYPE){
            super(context);
            this.SCAN_FILE_PATH = SCAN_FILE_PATH;
            if (SCAN_FILE_PATH == null){
                this.SCAN_FILE_PATH = FilePaths.ROOT_DIR;
            }
            this.SCAN_FILE_MIME_TYPE = SCAN_FILE_MIME_TYPE;
            if (SCAN_FILE_MIME_TYPE == null){
                this.SCAN_FILE_MIME_TYPE = "*/*";
            }
            connection = new MediaScannerConnection(this, this);
            connection.connect();
        }

        @Override
        public void onMediaScannerConnected() {
            MyLog.d("onMediaScannerConnected");
            connection.scanFile(SCAN_FILE_PATH, SCAN_FILE_MIME_TYPE);
        }

        @Override
        public void onScanCompleted(String path, Uri uri) {
            MyLog.d("onScanCompleted" + " URI : " + uri.getPath());
            connection.disconnect();
        }
    }
FilesScanner.with(this, path, "image/*");
```

答:
```<code>i used this code to crop image but its not working in api level 28 and 29 can anyone suggest where getting wrong.

  File tempDir = Environment.getExternalStorageDirectory();
                    tempDir = new File(tempDir.getAbsolutePath() + "/.temp/");
                    tempDir.mkdir();
                    File tempFile = null;
                    try {
                        tempFile = File.createTempFile("Trendii", ".png", tempDir);

                        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
                        byte[] bitmapData = bytes.toByteArray();

                        //write the bytes in file
                        FileOutputStream fos = new FileOutputStream(tempFile);
                        fos.write(bitmapData);
                        fos.flush();
                        fos.close();

                        float height = 0, width = 0;

                        if (bitmap != null) {
                            height = bitmap.getHeight();
                            width = bitmap.getWidth();
                        }

                        Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
                        Crop.of(Uri.fromFile(tempFile), destination, inspirationId, height, width).asSquare().start(InspirationDetailsActivity.this);

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onPermissionDenied(PermissionDeniedResponse response) {
                    showSettingsDialog();
                }

                @Override
                public void onPermissionRationaleShouldBeShown(PermissionRequest permission, PermissionToken token) {
                    token.continuePermissionRequest();
                }
            }).check();
        } else {

            File tempDir = Environment.getExternalStorageDirectory();
            tempDir = new File(tempDir.getAbsolutePath() + "/.temp/");
            tempDir.mkdir();
            File tempFile = null;
            try {
                tempFile = File.createTempFile("Trendii", ".png", tempDir);

                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
                byte[] bitmapData = bytes.toByteArray();

                //write the bytes in file
                FileOutputStream fos = new FileOutputStream(tempFile);
                fos.write(bitmapData);
                fos.flush();
                fos.close();

                float height = 0, width = 0;

                if (bitmap != null) {
                    height = bitmap.getHeight();
                    width = bitmap.getWidth();
                }

                Uri destination = Uri.fromFile(new File(getCacheDir(), "cropped"));
                Crop.of(Uri.fromFile(tempFile), destination, inspirationId, height, width).asSquare().start(this);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
</code>```

Body:
I'm scanning files using MediaScanner. But API 28 and 29 don't work.

context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, file));

I used Broadcast, but it didn't work the same way. Because it is "deprecated".

java public static class FilesScanner extends ContextWrapper implements MediaScannerConnection.MediaScannerConnectionClient{

        private MediaScannerConnection connection = null;
        private String SCAN_FILE_PATH = "";
        private String SCAN_FILE_MIME_TYPE = "*/*";

        public static FilesScanner with(Context context, String SCAN_FILE_PATH){ return new FilesScanner(context, SCAN_FILE_PATH, "*/*"); }
        public static FilesScanner with(Context context, String SCAN_FILE_PATH, String SCAN_FILE_MIME_TYPE){ return new FilesScanner(context, SCAN_FILE_PATH, SCAN_FILE_MIME_TYPE); }
        private FilesScanner(Context context, String SCAN_FILE_PATH, String SCAN_FILE_MIME_TYPE){
            super(context);
            this.SCAN_FILE_PATH = SCAN_FILE_PATH;
            if (SCAN_FILE_PATH == null){
                this.SCAN_FILE_PATH = FilePaths.ROOT_DIR;
            }
            this.SCAN_FILE_MIME_TYPE = SCAN_FILE_MIME_TYPE;
            if (SCAN_FILE_MIME_TYPE == null){
                this.SCAN_FILE_MIME_TYPE = "*/*";
            }
            connection = new MediaScannerConnection(this, this);
            connection.connect();
        }

        @Override
        public void onMediaScannerConnected() {
            MyLog.d("onMediaScannerConnected");
            connection.scanFile(SCAN_FILE_PATH, SCAN_FILE_MIME_TYPE);
        }

        @Override
        public void onScanCompleted(String path, Uri uri) {
            MyLog.d("onScanCompleted" + " URI : " + uri.getPath());
            connection.disconnect();
        }
    }
FilesScanner.with(this, path, "image/*");


问:
Automating a third party application - Systreeview32 reports 0 items, yet has nodes
I am working to automate several applications. One depends on the output of another.
The problem I am running into is that when I try to access the Treeview to get additional info, the count returns 0.

If I look at it visibly, it show quite a few items.
If I look at it with Winspector, it reports 0 visible items.

How can I gather this info? This is the info that is gathered dynamically and from several places. I cannot access the databases (that would be nice, but since some of the info is dynamic, it is not possible).

Here is the output that Winspector gives me:

```<code>Properties for window: 0x00021806

Class Name:         SysTreeView32

Rectangle:          213, 180, 1038, 375

Size:               825, 195

Client Rectangle:   0, 0, 821, 191

Client Size:        821, 191

Styles:             WS_CHILD,
                    WS_VISIBLE,
                    WS_CLIPSIBLINGS,
                    WS_CLIPCHILDREN,
                    WS_TABSTOP,

StylesEx:           WS_EX_NOPARENTNOTIFY,
                    WS_EX_CLIENTEDGE,
                    WS_EX_LEFT,
                    WS_EX_LTRREADING,
                    WS_EX_RIGHTSCROLLBAR

ID:                 0

Properties:         Atom: #43288 0xFFFFFFFF (-1)

Class specific:     Visible items:0,
                    Total items: 0
                    Window is Ansi

Owner EXE           c:\csg\acsr\XBOI.EXE
</code>```

Any ideas how I can retrieve the node info and items?
I am using VBA (access) with API calls with sendmessage.

Here is my code that I am using to test item count:

```<code>Sub testtree(mytv As Long)

Dim z As Long

Dim wClass As String, wText As String

    Dim hWndTvw  As Long

    Dim hNode As Long

    Dim varReturn As Long

    Dim tvcount As Long

    Dim hchild As Long

    Dim j As Integer

    hchild = mytv

    wClass = Space(64)

    j = GetClassName(hchild, wClass, 63)

    wClass = Left(wClass, j)

    wText = Space(256)

    j = SendMessageS(hchild, WM_GETTEXT, 255, wText)

    wText = Left(wText, j)

    Debug.Print wText

z = SendMessage(mytv, TVM_GETCOUNT, 0&, 0&)

MsgBox z

End Sub
</code>```

Thanks!

答:
You should consider using TVM_GETNEXTITEM message to enumerate the tree's nodes: first call it with TVGN_ROOT flag to get the root node, then use TVGN_CHILD and TVGN_NEXT flags to walk through the nodes. This message returns you the item's handle.

When you've got the item's handle, use TVM_GETITEM message to retrieve the associated data you're interested in (e.g. item's text).

You should read that 2 links carefully for more info on using that messages.

P.S. The problem is, the TVM_GETITEM message uses TVITEM structure with pointers, and I'm not sure it'll be easy to use from the VBA (unlike e.g. C, C++, even C#/VB.NET is IMO more suitable for that). In the worst case (i.e. unless you know something about the VBA I'm not aware of: last time I've dealt with VBA was about 2004), you'll need to develop a small COM object using C++/ATL for this single task, and redistrubute & register it along with your software. Or look for the 3-rd party components.

Body:
I am working to automate several applications. One depends on the output of another.
The problem I am running into is that when I try to access the Treeview to get additional info, the count returns 0.

If I look at it visibly, it show quite a few items.
If I look at it with Winspector, it reports 0 visible items.

How can I gather this info? This is the info that is gathered dynamically and from several places. I cannot access the databases (that would be nice, but since some of the info is dynamic, it is not possible).

Here is the output that Winspector gives me:

Properties for window: 0x00021806

Class Name:         SysTreeView32

Rectangle:          213, 180, 1038, 375

Size:               825, 195

Client Rectangle:   0, 0, 821, 191

Client Size:        821, 191

Styles:             WS_CHILD,
                    WS_VISIBLE,
                    WS_CLIPSIBLINGS,
                    WS_CLIPCHILDREN,
                    WS_TABSTOP,

StylesEx:           WS_EX_NOPARENTNOTIFY,
                    WS_EX_CLIENTEDGE,
                    WS_EX_LEFT,
                    WS_EX_LTRREADING,
                    WS_EX_RIGHTSCROLLBAR

ID:                 0

Properties:         Atom: #43288 0xFFFFFFFF (-1)

Class specific:     Visible items:0,
                    Total items: 0
                    Window is Ansi

Owner EXE           c:\csg\acsr\XBOI.EXE

Any ideas how I can retrieve the node info and items?
I am using VBA (access) with API calls with sendmessage.

Here is my code that I am using to test item count:

Sub testtree(mytv As Long)

Dim z As Long

Dim wClass As String, wText As String

    Dim hWndTvw  As Long

    Dim hNode As Long

    Dim varReturn As Long

    Dim tvcount As Long

    Dim hchild As Long

    Dim j As Integer

    hchild = mytv

    wClass = Space(64)

    j = GetClassName(hchild, wClass, 63)

    wClass = Left(wClass, j)

    wText = Space(256)

    j = SendMessageS(hchild, WM_GETTEXT, 255, wText)

    wText = Left(wText, j)

    Debug.Print wText

z = SendMessage(mytv, TVM_GETCOUNT, 0&, 0&)

MsgBox z

End Sub

Thanks!


问:
Promise in Angular 9
I'm trying to write a synchronous function call in Angular using a Promise, but it still gets a different result than expected.
I have 2 functions that use the service that download data from the API:

```<code>getData1(shortcut: string): void {
  this.apiServ.getPrice(shortcut).subscribe(
    (price: CurrentPrice) => {
      this.price = price;
      console.log(1);
    },
    error => this.error = error
  );
}

getData2(shortcut: string): void {
  this.apiServ.getPrice(shortcut).subscribe(
    (price: CurrentPrice) => {
      this.price = price;
      console.log(2);
    },
    error => this.error = error
  );
}
</code>```

I'm trying to make the next function call after the response is completed. So:

```<code>data(shortcuts) {
  this.getData1(shortcuts[0]);
  this.getData2(shortcuts[1]);
}

ngOnInit() {
  const myPromise = new Promise((resolve) => {
    this.data(this.shortcuts);
    resolve(3)
  });
  myPromise.then((value) => {console.log(value)});
}

</code>```

But my browser prints this call order:

```<code>3
1
2
</code>```

What am I doing wrong?

I also tried to use callbacks but the effect is always the same.

答:
Because they are promises you need to respect their resolve time, it means to wait until they are completed and that means you can't call them as a normal function when you rely on their result.

Also because it's an angular app try to convert them to rxjs stream via from function.

getData1(shortcut: string): Observable<CurrentPrice> { // <- return stream
  return this.apiServ.getPrice(shortcut).pipe(
    tap(console.log, console.log), // logs emits and errors
  );
}

getData2(shortcut: string): Observable<CurrentPrice> { // <- return stream
  return this.apiServ.getPrice(shortcut).pipe(
    tap(console.log, console.log), // logs emits and errors
  );
}

data(shortcuts): Observable<[CurrentPrice, CurrentPrice]> { // <- return stream
  return combineLatest([
    this.getData1(shortcuts[0]),
    this.getData2(shortcuts[1]),
  ]);
}

ngOnInit() {
  const myPromise = new Promise((resolve, error) => {
    // wait until completed
    this.data(this.shortcuts).pipe(
      take(1), // <- in promise we need just 1 emit
    ).subscribe(prices => resolve(prices), error);
  });
  myPromise.then((value) => {console.log(value)}); // profit
}
```

Title: Promise in Angular 9

Body:
I'm trying to write a synchronous function call in Angular using a Promise, but it still gets a different result than expected.
I have 2 functions that use the service that download data from the API:

getData1(shortcut: string): void {
  this.apiServ.getPrice(shortcut).subscribe(
    (price: CurrentPrice) => {
      this.price = price;
      console.log(1);
    },
    error => this.error = error
  );
}

getData2(shortcut: string): void {
  this.apiServ.getPrice(shortcut).subscribe(
    (price: CurrentPrice) => {
      this.price = price;
      console.log(2);
    },
    error => this.error = error
  );
}

I'm trying to make the next function call after the response is completed. So:

data(shortcuts) {
  this.getData1(shortcuts[0]);
  this.getData2(shortcuts[1]);
}

ngOnInit() {
  const myPromise = new Promise((resolve) => {
    this.data(this.shortcuts);
    resolve(3)
  });
  myPromise.then((value) => {console.log(value)});
}

But my browser prints this call order:

3
1
2

What am I doing wrong?

I also tried to use callbacks but the effect is always the same.


问:
C# Linq OrderBy based on condition
I have a foreach loop that I want to change:

foreach (var line in lines.OrderBy(x=> x.ColA))

If a condition is met, then instead of ordering by ColA, I want to order by ColB.

I know this could be done like the following:

```<code>var orderLines = new List<OrderLines>();
if (condition)
    orderLines = lines.OrderBy(x => x.ColB).ToList();
else
    orderLines = lines.OrderBy(x => x.ColA).ToList(); ;

foreach (var line in orderLines)
</code>```

But I am sure there is a more elegant solution.

答:
Install NuGet System.Linq.Dynamic and you can pass property name as string to OrderBy like below.

Usage list.AsQueryable().OrderBy("PropertyName1 SortOrder, ropertyName SortOrder"). Where PropertyName will be ColA  ColB. And SortOrder will be ASC DESC.

Add using System.Linq.Dynamic;

foreach (var line in lines.AsQueryable().OrderBy(condition ? "ColB" : "ColA")

For .Net Core install NuGet System.Linq.Dynamic.Core.

Add using System.Linq.Dynamic.Core;

foreach (var line in lines.AsQueryable().OrderBy(condition ? "ColB" : "ColA")

For a better practice rather than providing PropertyName as string use nameof(Class.Property) like in your case nameof(OrderLines.ColA). So in case you change ColA property it will show Builderror and you will not get run time exception.

foreach (var line in lines.AsQueryable().OrderBy(condition ? nameof(OrderLines.ColB) : nameof(OrderLines.ColA))

Title: C# Linq OrderBy based on condition

Body:
I have a foreach loop that I want to change:

foreach (var line in lines.OrderBy(x=> x.ColA))

If a condition is met, then instead of ordering by ColA, I want to order by ColB.

I know this could be done like the following:

var orderLines = new List<OrderLines>();
if (condition)
    orderLines = lines.OrderBy(x => x.ColB).ToList();
else
    orderLines = lines.OrderBy(x => x.ColA).ToList(); ;

foreach (var line in orderLines)

But I am sure there is a more elegant solution.


问:
Unable to add an array index
I would like to allocate names for the index in an array while using for loop. how can i achieve this. please guide me.

```<code>// using in a http response
   for (let i = 0; i <= 6; i++) {
            this.sf.push({f(i) : // do something)
          };
</code>```

i want to get something like

```<code>f0: 1,
f1: 5,
f2: 9
</code>```

答:
Do you want to turn the array, [1,5,9,...], into an object, {f0: 1, f1: 5, f2:9, ...}?

If so, you can use Array.reduce() for the conversion:

```<code>const test = [1,5,9,10,15,25];

const result = test.reduce((accum, elem, index) => {
  accum[`f${index}`] = elem;
  return accum;

}, {});

</code>```

UPDATE:

Turns out, you can use the same method to keep it as an Array:

```<code>const arrayResult = test.reduce((accum, elem, index) => {
  accum[`f${index}`] = elem;
  return accum;

}, []);

arrayResult; // [f0: 1, f0: 5, ...]
</code>```

Source

Title: Unable to add an array index

Body:
I would like to allocate names for the index in an array while using for loop. how can i achieve this. please guide me.

// using in a http response
   for (let i = 0; i <= 6; i++) {
            this.sf.push({f(i) : // do something)
          };

i want to get something like

f0: 1,
f1: 5,
f2: 9

Body:
Do you want to turn the array, [1,5,9,...], into an object, {f0: 1, f1: 5, f2:9, ...}?

If so, you can use Array.reduce() for the conversion:

const test = [1,5,9,10,15,25];

const result = test.reduce((accum, elem, index) => {
  accum[`f${index}`] = elem;
  return accum;

}, {});

UPDATE:

Turns out, you can use the same method to keep it as an Array:

const arrayResult = test.reduce((accum, elem, index) => {
  accum[`f${index}`] = elem;
  return accum;

}, []);

arrayResult; // [f0: 1, f0: 5, ...]

Source


问:
ASP.Net run exe on server from an API call
I have a WebAPI that works great but need to add the ability to call to an EXE on the server to run some tasks with Video, the server is our machine and running IIS to host the WebAPI.

I have tried it working with Process() and the calls make it to the cmd.exe file I have written but the issue is that the user is IUSER and this won't work as the Video processing needs to use system hardware so needs to be the current logged in Windows User.

I don't want to give the IUSER this privilege for obvious security reasons so I am looking for another way to call and pass data to the an EXE or background task (Short running <3seconds) and for that process to reply with the results.

It's all on the server which we have full control over.

Current Code:

```<code>string exeLoc = Environment.ExpandEnvironmentVariables(baseEXELocation);
using var process = new Process();
process.StartInfo.FileName = exeLoc;
process.StartInfo.Arguments = $"{command}";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += (sender, data) =>
{
   if (!String.IsNullOrEmpty(data.Data))
   {
      Console.WriteLine(data.Data);
      consoleData += data.Data;
    }
};
process.Start();
process.BeginOutputReadLine();
var exited = process.WaitForExit(1000 * 10);     // (optional) wait up to 10 seconds
</code>```

Thanks

答:
You could try to use the impersonation in iis:

```<code><identity impersonate="true" />
</code>```

https://support.microsoft.com/en-us/help/306158/how-to-implement-impersonation-in-an-asp-net-application

or assign the administrator permission to the application pool by using application pool advance setting -> identity to the custom account.

or You can try using the verb runas in Process.Start to execute the exe file as an Administrator.

```<code>ProcessStartInfo proc = new ProcessStartInfo();
proc.WindowStyle = ProcessWindowStyle.Normal;
proc.FileName = myExePath;
proc.CreateNoWindow = false;
proc.UseShellExecute = false;
proc.Verb = "runas"; //this is how you pass this verb
</code>```

Body:
I have a WebAPI that works great but need to add the ability to call to an EXE on the server to run some tasks with Video, the server is our machine and running IIS to host the WebAPI.

I have tried it working with Process() and the calls make it to the cmd.exe file I have written but the issue is that the user is IUSER and this won't work as the Video processing needs to use system hardware so needs to be the current logged in Windows User.

I don't want to give the IUSER this privilege for obvious security reasons so I am looking for another way to call and pass data to the an EXE or background task (Short running <3seconds) and for that process to reply with the results.

It's all on the server which we have full control over.

Current Code:

string exeLoc = Environment.ExpandEnvironmentVariables(baseEXELocation);
using var process = new Process();
process.StartInfo.FileName = exeLoc;
process.StartInfo.Arguments = $"{command}";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += (sender, data) =>
{
   if (!String.IsNullOrEmpty(data.Data))
   {
      Console.WriteLine(data.Data);
      consoleData += data.Data;
    }
};
process.Start();
process.BeginOutputReadLine();
var exited = process.WaitForExit(1000 * 10);     // (optional) wait up to 10 seconds

Thanks

Body:
You could try to use the impersonation in iis:

<identity impersonate="true" />

https://support.microsoft.com/en-us/help/306158/how-to-implement-impersonation-in-an-asp-net-application

or assign the administrator permission to the application pool by using application pool advance setting -> identity to the custom account.

or You can try using the verb runas in Process.Start to execute the exe file as an Administrator.

ProcessStartInfo proc = new ProcessStartInfo();
proc.WindowStyle = ProcessWindowStyle.Normal;
proc.FileName = myExePath;
proc.CreateNoWindow = false;
proc.UseShellExecute = false;
proc.Verb = "runas"; //this is how you pass this verb


问:
how to Convert X and Y to lat and long
I have a table called IK_TEMP and it contains columns called data, range .

```<code>        String sql = "SELECT DATA, RANGE FROM IK_TEMP";

        try (Connection conn = this.connect();
             Statement stmt  = conn.createStatement();
             ResultSet rs    = stmt.executeQuery(sql)){

            // loop through the result set
            while (rs.next()) {
                System.out.println(rs.getString("DATA") +  "\t" +
                                   rs.getBytes("RANGE"));
               fromBytes(rs.getBytes("RANGE"));
            }
</code>```

The RANGE field(binary / BLOB) field is already encoded using binary from arcGIS and saved in the Database.
http://www.geopackage.org/spec120/#gpb_format

I want to decode this RANGE field using java.

Here I have tried with  fromBytes method

```<code>public void fromBytes(byte[] bytes) {
            this.bytes = bytes;

            ByteReader reader = new ByteReader(bytes);

            // Get 2 bytes as the magic number and validate
            String magic = null;
            try {
                magic = reader.readString(2);
            } catch (UnsupportedEncodingException e) {
                throw new GeoPackageException(
                        "Unexpected GeoPackage Geometry magic number character encoding: Expected: "
                                + GeoPackageConstants.GEOMETRY_MAGIC_NUMBER);
            }
            if (!magic
                    .equals(GeoPackageConstants.GEOMETRY_MAGIC_NUMBER)) {
                throw new GeoPackageException(
                        "Unexpected GeoPackage Geometry magic number: "
                                + magic
                                + ", Expected: "
                                + GeoPackageConstants.GEOMETRY_MAGIC_NUMBER);
            }

            // Get a byte as the version and validate, value of 0 = version 1
            byte version = reader.readByte();
            if (version != GeoPackageConstants.GEOMETRY_VERSION_1) {
                throw new GeoPackageException(
                        "Unexpected GeoPackage Geometry version: "
                                + version
                                + ", Expected: "
                                + GeoPackageConstants.GEOMETRY_VERSION_1);
            }

            // Get a flags byte and then read the flag values
            byte flags = reader.readByte();
            int envelopeIndicator = readFlags(flags);
            reader.setByteOrder(byteOrder);

            // Read the 5th - 8th bytes as the srs id
            srsId = reader.readInt();

            // Read the envelope
            envelope = readEnvelope(envelopeIndicator, reader);

            // Save off where the WKB bytes start
            wkbGeometryIndex = reader.getNextByte();

            // Read the Well-Known Binary Geometry if not marked as empty
            if (!empty) {
                geometry = GeometryReader.readGeometry(reader);
            }

        }
</code>```

I am getting x and y coordinates and geometryType in geometry object, But how can I get lat and long from this

In one of the example they have given in JS reff.

```<code>for item in (GeometryDataXYValue)!{
        let xValue = item.paths?.ofX
        let yValue = item.paths?.ofY

        //recieve x y point
        currentPoint = AGSPoint(x: xValue!, y: yValue!, spatialReference: AGSSpatialReference.webMercator())

        //convert to lat long by AGSSpatialReference.wgs84()

       if  let aReference = AGSGeometryEngine.projectGeometry(currentPoint!, to: AGSSpatialReference.wgs84()) as? AGSPoint {
            currentPoint = aReference
        }
    }
    var long:Double = currentPoint!.x
    var lat: Double = currentPoint!.y
    print("value long lat =  \(long , lat)")
}
</code>```

But I want the same conversion in java.
This is another example

example

答:
You can get the lat and long by using the  geotools library.

```<code>Coordinate coordinate = new Coordinate(geometry.getEnvelope().getMaxX(), geometry.getEnvelope().getMaxY());
            MathTransform transform;
            Coordinate targetGeometry;
            double latitude;
            double longitude;
            try {

            //sourceCRS is to convert the X and Y coordinates to lat long
            CoordinateReferenceSystem sourceCRS = CRS.decode("EPSG:25832");
            CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:4326");

                transform = CRS.findMathTransform(sourceCRS, targetCRS, false);
                targetGeometry = JTS.transform(coordinate, coordinate, transform);
                latitude = targetGeometry.getX();
                longitude = targetGeometry.getY();
            } catch (FactoryException | TransformException e) {
                e.printStackTrace();
            }
        }
</code>```

Title: how to Convert X and Y to lat and long

Body:
I have a table called IK_TEMP and it contains columns called data, range .

        String sql = "SELECT DATA, RANGE FROM IK_TEMP";

        try (Connection conn = this.connect();
             Statement stmt  = conn.createStatement();
             ResultSet rs    = stmt.executeQuery(sql)){

            // loop through the result set
            while (rs.next()) {
                System.out.println(rs.getString("DATA") +  "\t" +
                                   rs.getBytes("RANGE"));
               fromBytes(rs.getBytes("RANGE"));
            }

The RANGE field(binary / BLOB) field is already encoded using binary from arcGIS and saved in the Database.
http://www.geopackage.org/spec120/#gpb_format

I want to decode this RANGE field using java.

Here I have tried with  fromBytes method

public void fromBytes(byte[] bytes) {
            this.bytes = bytes;

            ByteReader reader = new ByteReader(bytes);

            // Get 2 bytes as the magic number and validate
            String magic = null;
            try {
                magic = reader.readString(2);
            } catch (UnsupportedEncodingException e) {
                throw new GeoPackageException(
                        "Unexpected GeoPackage Geometry magic number character encoding: Expected: "
                                + GeoPackageConstants.GEOMETRY_MAGIC_NUMBER);
            }
            if (!magic
                    .equals(GeoPackageConstants.GEOMETRY_MAGIC_NUMBER)) {
                throw new GeoPackageException(
                        "Unexpected GeoPackage Geometry magic number: "
                                + magic
                                + ", Expected: "
                                + GeoPackageConstants.GEOMETRY_MAGIC_NUMBER);
            }

            // Get a byte as the version and validate, value of 0 = version 1
            byte version = reader.readByte();
            if (version != GeoPackageConstants.GEOMETRY_VERSION_1) {
                throw new GeoPackageException(
                        "Unexpected GeoPackage Geometry version: "
                                + version
                                + ", Expected: "
                                + GeoPackageConstants.GEOMETRY_VERSION_1);
            }

            // Get a flags byte and then read the flag values
            byte flags = reader.readByte();
            int envelopeIndicator = readFlags(flags);
            reader.setByteOrder(byteOrder);

            // Read the 5th - 8th bytes as the srs id
            srsId = reader.readInt();

            // Read the envelope
            envelope = readEnvelope(envelopeIndicator, reader);

            // Save off where the WKB bytes start
            wkbGeometryIndex = reader.getNextByte();

            // Read the Well-Known Binary Geometry if not marked as empty
            if (!empty) {
                geometry = GeometryReader.readGeometry(reader);
            }

        }

I am getting x and y coordinates and geometryType in geometry object, But how can I get lat and long from this

In one of the example they have given in JS reff.

for item in (GeometryDataXYValue)!{
        let xValue = item.paths?.ofX
        let yValue = item.paths?.ofY

        //recieve x y point
        currentPoint = AGSPoint(x: xValue!, y: yValue!, spatialReference: AGSSpatialReference.webMercator())

        //convert to lat long by AGSSpatialReference.wgs84()

       if  let aReference = AGSGeometryEngine.projectGeometry(currentPoint!, to: AGSSpatialReference.wgs84()) as? AGSPoint {
            currentPoint = aReference
        }
    }
    var long:Double = currentPoint!.x
    var lat: Double = currentPoint!.y
    print("value long lat =  \(long , lat)")
}

But I want the same conversion in java.
This is another example

example

Body:
You can get the lat and long by using the  geotools library.

Coordinate coordinate = new Coordinate(geometry.getEnvelope().getMaxX(), geometry.getEnvelope().getMaxY());
            MathTransform transform;
            Coordinate targetGeometry;
            double latitude;
            double longitude;
            try {

            //sourceCRS is to convert the X and Y coordinates to lat long
            CoordinateReferenceSystem sourceCRS = CRS.decode("EPSG:25832");
            CoordinateReferenceSystem targetCRS = CRS.decode("EPSG:4326");

                transform = CRS.findMathTransform(sourceCRS, targetCRS, false);
                targetGeometry = JTS.transform(coordinate, coordinate, transform);
                latitude = targetGeometry.getX();
                longitude = targetGeometry.getY();
            } catch (FactoryException | TransformException e) {
                e.printStackTrace();
            }
        }


问:
TFS 2010 Change Log
Is there an automated way to create a change log using TFS 2010 and the version history of the files?  I'd like to pull in all the comments that were entered for each changeset either between a label (or a specific date) and the current version, or between two labels (or two specific dates).</p>

答:
The tf.exe command line tool with give you the history or more or more items between two points in the history where those points can be specified by date, label or changeset number.

Eg.

```<code>tf history /version:C5~C8 MyClass.cs
</code>```

See the help on MSDN: http://msdn.microsoft.com/en-us/library/yxtbh4yh.aspx

Title: TFS 2010 Change Log

Body:
The tf.exe command line tool with give you the history or more or more items between two points in the history where those points can be specified by date, label or changeset number.

Eg.

tf history /version:C5~C8 MyClass.cs

See the help on MSDN: http://msdn.microsoft.com/en-us/library/yxtbh4yh.aspx


问:
Change loading indicator Offset in Xamarin.Forms RefreshView
On Xamarin.Forms (iOS Android), I need to change the loading-indicator position on the RefreshView. I need to add offset, so the indicator is visible if you have a bar overlapping the ScrollView-RefreshView combo and trigger pullOnRefresh.

Loading-indicator in the top edge

EDIT: thanks to  Junior Jiang - MSFT- Android solution

I also implement a solution for xamarin.iOS

```<code>[assembly: ExportRenderer(typeof(RefreshView), typeof(CustomRefreshViewRenderer))]
namespace CustomRefresh.iOS {
public class CustomRefreshViewRenderer : RefreshViewRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<RefreshView> e)
    {
        base.OnElementChanged(e);

        foreach (var nativeView in Subviews)
            updateRefreshSettings(nativeView);

    }

    void updateRefreshSettings(UIView view) {
        if (view is UIScrollView)
        {
            var scrollView = view as UIScrollView;
            if (scrollView.RefreshControl != null)
            {
                var bounds = scrollView.RefreshControl.Bounds;
                scrollView.RefreshControl.Bounds = new CGRect(bounds.X, -(100), bounds.Width, bounds.Height);
            }
        }
        //add more scrollable view types
    }
}
</code>```

}

答:
You can custom a RefreshViewRenderer to achieve that .

In Android , there is a MOriginalOffsetTop to modify the offset of loading indicator . In addition , also can use SetProgressViewOffset to set the start and end position of indicator .

Code as follow :

```<code>using Android.Content;
using RefreshViewDemo.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(RefreshView), typeof(CustomRefreshViewRenderer))]
namespace RefreshViewDemo.Droid
{
    public class CustomRefreshViewRenderer : RefreshViewRenderer
    {

        public CustomRefreshViewRenderer(Context context) : base(context)
        {
            MOriginalOffsetTop = 100;

           // SetProgressViewOffset(true, 100, 101);
        }

    }
}
</code>```

In iOS , the loading indicator belong to UIRefreshControl of UIScrollView , there is no direct way to change it's offset . Unless override all content view in Renderer then can achieve that . You can refer this Xamarin.Forms/Xamarin.Forms.Platform.iOS/Renderers/RefreshViewRenderer.cs to know what the RefreshView is made of .

====================Update=====================

Shared code is based on this official sample :https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/userinterface-refreshviewdemo/

For Android , just need to create a CustomRefreshViewRenderer class in android solution .

The effect of SetProgressViewOffset(true, 100, 101) , it seems like the indicator not moving :

Body:
On Xamarin.Forms (iOS Android), I need to change the loading-indicator position on the RefreshView. I need to add offset, so the indicator is visible if you have a bar overlapping the ScrollView-RefreshView combo and trigger pullOnRefresh.

Loading-indicator in the top edge

EDIT: thanks to  Junior Jiang - MSFT- Android solution

I also implement a solution for xamarin.iOS

[assembly: ExportRenderer(typeof(RefreshView), typeof(CustomRefreshViewRenderer))]
namespace CustomRefresh.iOS {
public class CustomRefreshViewRenderer : RefreshViewRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<RefreshView> e)
    {
        base.OnElementChanged(e);

        foreach (var nativeView in Subviews)
            updateRefreshSettings(nativeView);

    }

    void updateRefreshSettings(UIView view) {
        if (view is UIScrollView)
        {
            var scrollView = view as UIScrollView;
            if (scrollView.RefreshControl != null)
            {
                var bounds = scrollView.RefreshControl.Bounds;
                scrollView.RefreshControl.Bounds = new CGRect(bounds.X, -(100), bounds.Width, bounds.Height);
            }
        }
        //add more scrollable view types
    }
}

}

Body:
You can custom a RefreshViewRenderer to achieve that .

In Android , there is a MOriginalOffsetTop to modify the offset of loading indicator . In addition , also can use SetProgressViewOffset to set the start and end position of indicator .

Code as follow :

using Android.Content;
using RefreshViewDemo.Droid;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
[assembly: ExportRenderer(typeof(RefreshView), typeof(CustomRefreshViewRenderer))]
namespace RefreshViewDemo.Droid
{
    public class CustomRefreshViewRenderer : RefreshViewRenderer
    {

        public CustomRefreshViewRenderer(Context context) : base(context)
        {
            MOriginalOffsetTop = 100;

           // SetProgressViewOffset(true, 100, 101);
        }

    }
}

In iOS , the loading indicator belong to UIRefreshControl of UIScrollView , there is no direct way to change it's offset . Unless override all content view in Renderer then can achieve that . You can refer this Xamarin.Forms/Xamarin.Forms.Platform.iOS/Renderers/RefreshViewRenderer.cs to know what the RefreshView is made of .

====================Update=====================

Shared code is based on this official sample :https://learn.microsoft.com/en-us/samples/xamarin/xamarin-forms-samples/userinterface-refreshviewdemo/

For Android , just need to create a CustomRefreshViewRenderer class in android solution .

The effect of SetProgressViewOffset(true, 100, 101) , it seems like the indicator not moving :


问:
display a number of entries for a specific uid in wordpress
I want to display a number of entries for a specific uid.

this is my function but it can not display any value

```<code>function anscount()
{
    global $wpdb;
        $table_name = $wpdb->prefix.'pte_quiz';
                $sql = "SELECT Count(*) AS count FROM $table_name WHERE uid =1";
                    echo "Count Number: ";
}
add_action('init','anscount');
</code>```

答:
try this way brother : </p>

```<code>function anscount()
{
    global $wpdb;
    $table_name = $wpdb->prefix.'pte_quiz';
    $sql = "SELECT Count(*) AS count FROM $table_name WHERE uid =1";
    $myrow = $wpdb->get_results($sql);
    if (isset($myrow[0]) && isset($myrow[0]->count)) {
        echo "Count Number: ".$myrow[0]->count;
    }
}
add_action('init','anscount');
</code>```

Body:
I want to display a number of entries for a specific uid.

this is my function but it can not display any value

function anscount()
{
    global $wpdb;
        $table_name = $wpdb->prefix.'pte_quiz';
                $sql = "SELECT Count(*) AS count FROM $table_name WHERE uid =1";
                    echo "Count Number: ";
}
add_action('init','anscount');

Body:
try this way brother :

function anscount()
{
    global $wpdb;
    $table_name = $wpdb->prefix.'pte_quiz';
    $sql = "SELECT Count(*) AS count FROM $table_name WHERE uid =1";
    $myrow = $wpdb->get_results($sql);
    if (isset($myrow[0]) && isset($myrow[0]->count)) {
        echo "Count Number: ".$myrow[0]->count;
    }
}
add_action('init','anscount');


问:
Converting array<System::string^> to std::string*
I am new to C++/Cli, actually in the C# project I have string[] which I converted to array, Now I need to pass this unmanaged array into the native CPP file, i.e I want to convert this "array" to std::string*. How I can do that. I tried this below:

void functionA(cli::array^varA){

```<code>cli::pin_ptr<System::String^>varA_value = &varA[0];
    std::string* varA_value_final = varA_value;
</code>```

}

But it gives error saying: a value of type cli::pin_ptr cannot be used to initialize entity of type std::string*

答:
The managed class System::String is completely different from the unmanaged class std::string. The classes are completely different, and store completely different data. You cannot get a pointer to one and pretend it's the other.

Iterate over the cli::array<System::String^>, convert each element, and stick the results in a std::vector<std::string> or other unmanaged container. Grab a pointer to the first element. Use marshal_as<std::string>() to convert each element.

Body:
I am new to C++/Cli, actually in the C# project I have string[] which I converted to array, Now I need to pass this unmanaged array into the native CPP file, i.e I want to convert this "array" to std::string*. How I can do that. I tried this below:

void functionA(cli::array^varA){

cli::pin_ptr<System::String^>varA_value = &varA[0];
    std::string* varA_value_final = varA_value;

}

But it gives error saying: a value of type cli::pin_ptr cannot be used to initialize entity of type std::string*


问:
change image by click prev/next button
I am trying to change images in "div" by clicking buttons as like "carousel", but could not done and codes does not throw any error.  I could not yet understand what I am doing wrong.

I am calling java script function "setIndex" on clicking with parameters +1 or -1. In java code
i simply change image source as required and simply put display='block' followed by image source.

but the theme is not working and does not change image.

Please help.

My codes are as under:

```<code><!DOCTYPE html>
<html>
<head>
    <title>prev_next#</title>
</head>
<style>
    .divContainer{
        width: 85%;
        margin: auto;
        overflow: hidden;
    }
    #Middle{
        min-height: 460px;
    }
    #divMiddle{
        width: 90%;
        margin: auto;
        border: 2px red solid;
        overflow: hidden;
        max-height: 460px;
    }
    #divSlides{
        float: left;
        width: 100%;
        max-height: 455px;
    }
    #slideImage{
        height: 494px;
        width: 100%;
        margin: auto;
    }
    .alink-left, .alink-right{
        position: absolute;
        top:30%;
        width: auto;
        margin-top: 22px;
        font-size: 40px;
        color:red;
        border:none;
        user-select: none;
        border-radius: 3px 0 0 3px;
        text-decoration: none;
    }
    .alink-left{
       color:yellow;
       left:0;
       margin-left: 10%;
    }
    .alink-right{
        color:red;
        right: 90px;
    }
</style>
<body>
    <section id='Middle'>
        <div class="divContainer" id="divMiddle">
            <div id="divSlides">
                <img id="slideImage" src="../html-web/img/it-slide01.jpg">
                <a class="alink-left"   href="" onclick="setIndex(-1)"> < </a>
                <a class="alink-right"  href="" onclick="setIndex(+1)"> > </a>
            </div>
        </div>
    </section>
</body>
<script>
    var imageNo= 1;
    var ImageSource="";

    function setIndex(idx) {
        imageNo = imageNo + idx ;
        alert(imageNo)
        switch(imageNo){
            case 1:
              slideImage.display='none';
              ImageSource='../html-web/img/it-slide01.jpg';
              break;
            case 2:
              alert('case 2')
              slideImage.display='none';
              ImageSource='../html-web/img/it-slide02.jpg';
              break;
            case 3:
              slideImage.display='none';
              ImageSource='../html-web/img/it-slide03.jpg';
              break;
            case 4:
              slideImage.display='none';
              ImageSource='../html-web/img/it-slide04.jpg';
              break;
            case 5:
              slideImage.display='none';
              ImageSource= '../html-web/img/it-slide05.jpg';
              break;
            case 6:
              slideImage.display='none';
              ImageSource= '../html-web/img/it-slide06.jpg';
              break;
            default:
              slideImage.display='none';
              ImageSource='../html-web/img/it-slide01.jpg';
              if(imageNo>=6||imageNo<=1){imageNo=1}
              break;
        }  // switch
            document.getElementsByTagName('slideImage').display='block';
            document.getElementsByTagName('slideImage').src = ImageSource;
            //slideImage.display='block';
            //slideImage.src = ImageSource;
    } //function setIndex
</script>
</html>
</code>```

答:
I think this code would be better.

    var imageNo= 1
    var ImageSources=[
      '../html-web/img/it-slide01.jpg',
      '../html-web/img/it-slide02.jpg',
      '../html-web/img/it-slide03.jpg',
      '../html-web/img/it-slide04.jpg',
      '../html-web/img/it-slide05.jpg',
      '../html-web/img/it-slide06.jpg'
    ]

    function setIndex(idx) {
        imageNo = (imageNo + idx)%6
        console.log(imageNo)
        document.getElementById('slideImage').src = ImageSources[imageNo];
    } //function setIndex   ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>    .divContainer{
        width: 85%;
        margin: auto;
        overflow: hidden;
    }
    #Middle{
        min-height: 460px;
    }
    #divMiddle{
        width: 90%;
        margin: auto;
        border: 2px red solid;
        overflow: hidden;
        max-height: 460px;
    }
    #divSlides{
        float: left;
        width: 100%;
        max-height: 455px;
    }
    #slideImage{
        height: 494px;
        width: 100%;
        margin: auto;
    }
    .alink-left, .alink-right{
        position: absolute;
        top:30%;
        width: auto;
        margin-top: 22px;
        font-size: 40px;
        color:red;
        border:none;
        user-select: none;
        border-radius: 3px 0 0 3px;
        text-decoration: none;
    }
    .alink-left{
       color:yellow;
       left:0;
       margin-left: 10%;
    }
    .alink-right{
        color:red;
        right: 90px;
    }</code>```

<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>prev_next#</title>

                 <
                 >

```

Title: change image by click prev/next button

Body:
I am trying to change images in "div" by clicking buttons as like "carousel", but could not done and codes does not throw any error.  I could not yet understand what I am doing wrong.

I am calling java script function "setIndex" on clicking with parameters +1 or -1. In java code
i simply change image source as required and simply put display='block' followed by image source.

but the theme is not working and does not change image.

Please help.

My codes are as under:

<!DOCTYPE html>

    <title>prev_next#</title>

                 <
                 >

Body:
I think this code would be better.

    var imageNo= 1
    var ImageSources=[
      '../html-web/img/it-slide01.jpg',
      '../html-web/img/it-slide02.jpg',
      '../html-web/img/it-slide03.jpg',
      '../html-web/img/it-slide04.jpg',
      '../html-web/img/it-slide05.jpg',
      '../html-web/img/it-slide06.jpg'
    ]

    function setIndex(idx) {
        imageNo = (imageNo + idx)%6
        console.log(imageNo)
        document.getElementById('slideImage').src = ImageSources[imageNo];
    } //function setIndex

    .divContainer{
        width: 85%;
        margin: auto;
        overflow: hidden;
    }
    #Middle{
        min-height: 460px;
    }
    #divMiddle{
        width: 90%;
        margin: auto;
        border: 2px red solid;
        overflow: hidden;
        max-height: 460px;
    }
    #divSlides{
        float: left;
        width: 100%;
        max-height: 455px;
    }
    #slideImage{
        height: 494px;
        width: 100%;
        margin: auto;
    }
    .alink-left, .alink-right{
        position: absolute;
        top:30%;
        width: auto;
        margin-top: 22px;
        font-size: 40px;
        color:red;
        border:none;
        user-select: none;
        border-radius: 3px 0 0 3px;
        text-decoration: none;
    }
    .alink-left{
       color:yellow;
       left:0;
       margin-left: 10%;
    }
    .alink-right{
        color:red;
        right: 90px;
    }

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>prev_next#</title>
</head>
<style>
    .divContainer{
        width: 85%;
        margin: auto;
        overflow: hidden;
    }
    #Middle{
        min-height: 460px;
    }
    #divMiddle{
        width: 90%;
        margin: auto;
        border: 2px red solid;
        overflow: hidden;
        max-height: 460px;
    }
    #divSlides{
        float: left;
        width: 100%;
        max-height: 455px;
    }
    #slideImage{
        height: 494px;
        width: 100%;
        margin: auto;
    }
    .alink-left, .alink-right{
        position: absolute;
        top:30%;
        width: auto;
        margin-top: 22px;
        font-size: 40px;
        color:red;
        border:none;
        user-select: none;
        border-radius: 3px 0 0 3px;
        text-decoration: none;
    }
    .alink-left{
       color:yellow;
       left:0;
       margin-left: 10%;
    }
    .alink-right{
        color:red;
        right: 90px;
    }
</style>
<body>
    <section id='Middle'>
        <div class="divContainer" id="divMiddle">
            <div id="divSlides">
                <img id="slideImage" src="../html-web/img/it-slide01.jpg">
                <a class="alink-left"   href="#" onclick="setIndex(-1)"> < </a>
                <a class="alink-right"  href="#" onclick="setIndex(1)"> > </a>
            </div>
        </div>
    </section>
</body>

</html>


问:
Touch file then write to it in Node
How do I touch a file before writing to it?

Attempt

fs   = require 'fs'
os   = require 'os'
path = require 'path'

json_filepath = path.join os.tempdir(), 'cache', 'foo.json'

module.exports = (cb) ->
    fs.open json_filepath, 'w', 438, (err) -> # Touch, also tried with node-touch
        return cb err if err?
        fs.writeFile json_filepath, {foo: 'bar'}, {}, (err) ->
            #console.error 'Error writing cache: ', err
            cb err
```

<h3>Error</h3>

```{ [Error: ENOENT, open '/tmp/cache/foo.json']
  errno: 34,
  code: 'ENOENT',
  path: '/tmp/cache/foo.json' }
```

Which is a POSIX error (linux manpage, additionally implemented for Windows, e.g.: in libuv). It means: No such file or directory

答:
To answer original question</p>

```<code>fs.writeFileSync('sporks','','utf8','a')
</code>```

Title: Touch file then write to it in Node

Body:
How do I touch a file before writing to it?

Attempt

fs   = require 'fs'
os   = require 'os'
path = require 'path'

json_filepath = path.join os.tempdir(), 'cache', 'foo.json'

module.exports = (cb) ->
    fs.open json_filepath, 'w', 438, (err) -> # Touch, also tried with node-touch
        return cb err if err?
        fs.writeFile json_filepath, {foo: 'bar'}, {}, (err) ->
            #console.error 'Error writing cache: ', err
            cb err

Error

{ [Error: ENOENT, open '/tmp/cache/foo.json']
  errno: 34,
  code: 'ENOENT',
  path: '/tmp/cache/foo.json' }

Which is a POSIX error (linux manpage, additionally implemented for Windows, e.g.: in libuv). It means: No such file or directory

Body:
To answer original question

fs.writeFileSync('sporks','','utf8','a')