问:
queue in C array with pointers
I have tried to implement queue by array and pointers in C language. The queue
is modeled by C structure

```<code>// Circular Buffer
typedef struct{
    main_controller_req_t     buffer[BUFFER_SIZE];   // buffer
    uint16_t                  size;                  // length of the queue
    uint16_t                  count;                 // number of elements present in the queue
    main_controller_req_t     *p_head;               // pointer to head of the queue (read end)
    main_controller_req_t     *p_tail;               // pointer to tail of the queue (write end)
}circular_buffer_t;
</code>```

I have implemented function for queue initialization

```<code>void init_cb(circular_buffer_t *p_cb){

    p_cb->p_head = p_cb->buffer;
    p_cb->p_tail = p_cb->buffer;
    p_cb->count = 0;
    p_cb->size = BUFFER_SIZE;

}
</code>```

and function for inserting onto the queue

```<code>BOOL enqueue_cb(circular_buffer_t *p_cb, main_controller_req_t *p_enq_elem){

    if(p_cb->count < p_cb->size){

        // queue contains at least one free element

        taskENTER_CRITICAL();

            // insert the element at the tail of queue
            *(p_cb->p_tail) = *p_enq_elem;
            // incrementing modulo size
            p_cb->p_tail = (((p_cb->p_tail++) == (p_cb->buffer + p_cb->size)) ? (p_cb->buffer) : (p_cb->p_tail));
            // one element added
            p_cb->count++;

        taskEXIT_CRITICAL();

        return TRUE;

    }else{

        // queue is full
        return FALSE;

    }

}
</code>```

The enqueue_cb function works well until the tail reaches BUFFER_SIZE. Then the
program crashes and uC resets. The problem is in p_tail pointer update but I don't
understand why. Please can anybody help me? Thanks in advance.

答:
The problem is in your test...  You check for overrun, but before incrementing the pointer, this causes  p_cb->p_tailto go past the end of your circular buffer.

```<code> p_cb->p_tail = ((p_cb->p_tail++) == (p_cb->buffer + p_cb->size))
                    ? (p_cb->buffer)
                    : (p_cb->p_tail);
</code>```

You must test the value of tail after incrementing.

```<code> p_cb->p_tail = (++(p_cb->p_tail) >= (p_cb->buffer + p_cb->size))
                    ? p_cb->buffer
                    : p_cb->p_tail;
</code>```

As an aside, a linked list is not a very efficient way of implementing a circular buffer.  Have you considered using a simple fifo buffer implementation?

The fifo construct is so common, that it's useful to have a universal macro implementation for C.  It is thread-safe (no locks needed) if you only have one producer and one consumer.

These macros are very easy to optimize by the compiler.

It's a good tool to have in one's toolbox.

```<code>// save these macros in a header file.
#define fifo_reset(fifo) \
     { (fifo).head = (fifo).tail = (fifo).buffer; }

#define fifo_elements(fifo) \
    (sizeof((fifo).buffer) / sizeof((fifo).buffer[0])

#define fifo_count(fifo) \
    (((fifo).tail >= (fifo).head)) ? ((fifo).tail - (fifo).head) : (((fifo).tail - (fifo).head) + fifo_elements(fifo))

#define fifo_free_space(fifo) \
    (fifo_elements(fifo) - (fifo_count(fifo) + 1))

#define __fifo_advance(fifo, ptr) /* this is "private" */\
    (( ((ptr) + 1) < (fifo).buffer + fifo_elements(fifo))) ? ((ptr) + 1) : (fifo).buffer )

#define fifo_full(fifo) \
    (__fifo_advance(fifo, (fifo).head) == (fifo).tail)

#define fifo_empty(fifo) \
    ((fifo).head == (fifo).tail)

#define fifo_pop(fifo, el)  \
    ( (fifo).head = ((el) = *(fifo).head, __fifo_advance(fifo, (fifo).head)) )

#define fifo_push(fifo, el)  \
    ( (fifo).tail = (*((fifo).tail) = (el), __fifo_advance(fifo, (fifo).tail)) )

// Now, any struct with head, tail, and fixed-length buffer is a fifo.
struct char_fifo_128
{
  char buffer[128];
  char* head;
  char* tail;
};

struct main_controller_req_t
{
    // all data types are _movable_ using '='
    char any[128];
    int data;
    float more_data;
    char* dupstr;
};

#define BUFFER_SIZE 256

struct controller_fifo
{
  main_controller_req_t     buffer[BUFFER_SIZE];   // buffer
  main_controller_req_t*    head;
  main_controller_req_t*    tail;
};

int main()
{
  char c = 0;
  int elements_stored;
  controller_fifo queue;
  main_controller_req_t req;

  fifo_reset(queue);  // MUST call before using fifo

  // always check if space/data is available.
  if (!fifo_full(queue))
  {
      fifo_push(queue, req);
  }
  elements_stored = fifo_count(queue);

  if (!fifo_empty(queue))
  {
      fifo_pop(queue, req);
  }

  fifo_reset(queue);   // fifo reset is NOT thread-safe

  char_fifo_128* buffer = (char_fifo_128*)malloc(sizeof(char_fifo_128));

  fifo_reset(*buffer);

  if (!fifo_full(*buffer))
  {
      // ...
      fifo_push(*buffer, req);
  }
  elements_stored = fifo_count(*fifo);

  if (!fifo_empty(*buffer))
  {
      fifo_pop(*buffer, c);
  }

  free(buffer);
  return 0;
}
</code>```

Title: queue in C array with pointers

Body:
I have tried to implement queue by array and pointers in C language. The queue
is modeled by C structure

// Circular Buffer
typedef struct{
    main_controller_req_t     buffer[BUFFER_SIZE];   // buffer
    uint16_t                  size;                  // length of the queue
    uint16_t                  count;                 // number of elements present in the queue
    main_controller_req_t     *p_head;               // pointer to head of the queue (read end)
    main_controller_req_t     *p_tail;               // pointer to tail of the queue (write end)
}circular_buffer_t;

I have implemented function for queue initialization

void init_cb(circular_buffer_t *p_cb){

    p_cb->p_head = p_cb->buffer;
    p_cb->p_tail = p_cb->buffer;
    p_cb->count = 0;
    p_cb->size = BUFFER_SIZE;

}

and function for inserting onto the queue

BOOL enqueue_cb(circular_buffer_t *p_cb, main_controller_req_t *p_enq_elem){

    if(p_cb->count < p_cb->size){

        // queue contains at least one free element

        taskENTER_CRITICAL();

            // insert the element at the tail of queue
            *(p_cb->p_tail) = *p_enq_elem;
            // incrementing modulo size
            p_cb->p_tail = (((p_cb->p_tail++) == (p_cb->buffer + p_cb->size)) ? (p_cb->buffer) : (p_cb->p_tail));
            // one element added
            p_cb->count++;

        taskEXIT_CRITICAL();

        return TRUE;

    }else{

        // queue is full
        return FALSE;

    }

}

The enqueue_cb function works well until the tail reaches BUFFER_SIZE. Then the
program crashes and uC resets. The problem is in p_tail pointer update but I don't
understand why. Please can anybody help me? Thanks in advance.

Body:
The problem is in your test...  You check for overrun, but before incrementing the pointer, this causes  p_cb->p_tailto go past the end of your circular buffer.

 p_cb->p_tail = ((p_cb->p_tail++) == (p_cb->buffer + p_cb->size))
                    ? (p_cb->buffer)
                    : (p_cb->p_tail);

You must test the value of tail after incrementing.

 p_cb->p_tail = (++(p_cb->p_tail) >= (p_cb->buffer + p_cb->size))
                    ? p_cb->buffer
                    : p_cb->p_tail;

As an aside, a linked list is not a very efficient way of implementing a circular buffer.  Have you considered using a simple fifo buffer implementation?

The fifo construct is so common, that it's useful to have a universal macro implementation for C.  It is thread-safe (no locks needed) if you only have one producer and one consumer.

These macros are very easy to optimize by the compiler.

It's a good tool to have in one's toolbox.

// save these macros in a header file.
#define fifo_reset(fifo) \
     { (fifo).head = (fifo).tail = (fifo).buffer; }

#define fifo_elements(fifo) \
    (sizeof((fifo).buffer) / sizeof((fifo).buffer[0])

#define fifo_count(fifo) \
    (((fifo).tail >= (fifo).head)) ? ((fifo).tail - (fifo).head) : (((fifo).tail - (fifo).head) + fifo_elements(fifo))

#define fifo_free_space(fifo) \
    (fifo_elements(fifo) - (fifo_count(fifo) + 1))

#define __fifo_advance(fifo, ptr) /* this is "private" */\
    (( ((ptr) + 1) < (fifo).buffer + fifo_elements(fifo))) ? ((ptr) + 1) : (fifo).buffer )

#define fifo_full(fifo) \
    (__fifo_advance(fifo, (fifo).head) == (fifo).tail)

#define fifo_empty(fifo) \
    ((fifo).head == (fifo).tail)

#define fifo_pop(fifo, el)  \
    ( (fifo).head = ((el) = *(fifo).head, __fifo_advance(fifo, (fifo).head)) )

#define fifo_push(fifo, el)  \
    ( (fifo).tail = (*((fifo).tail) = (el), __fifo_advance(fifo, (fifo).tail)) )

// Now, any struct with head, tail, and fixed-length buffer is a fifo.
struct char_fifo_128
{
  char buffer[128];
  char* head;
  char* tail;
};

struct main_controller_req_t
{
    // all data types are _movable_ using '='
    char any[128];
    int data;
    float more_data;
    char* dupstr;
};

#define BUFFER_SIZE 256

struct controller_fifo
{
  main_controller_req_t     buffer[BUFFER_SIZE];   // buffer
  main_controller_req_t*    head;
  main_controller_req_t*    tail;
};

int main()
{
  char c = 0;
  int elements_stored;
  controller_fifo queue;
  main_controller_req_t req;

  fifo_reset(queue);  // MUST call before using fifo

  // always check if space/data is available.
  if (!fifo_full(queue))
  {
      fifo_push(queue, req);
  }
  elements_stored = fifo_count(queue);

  if (!fifo_empty(queue))
  {
      fifo_pop(queue, req);
  }

  fifo_reset(queue);   // fifo reset is NOT thread-safe

  char_fifo_128* buffer = (char_fifo_128*)malloc(sizeof(char_fifo_128));

  fifo_reset(*buffer);

  if (!fifo_full(*buffer))
  {
      // ...
      fifo_push(*buffer, req);
  }
  elements_stored = fifo_count(*fifo);

  if (!fifo_empty(*buffer))
  {
      fifo_pop(*buffer, c);
  }

  free(buffer);
  return 0;
}


来源: stackexchange

问:
list of entity, max date, max row_id
I have table in SQLServer.

I have list in c#, of entity id. (ex: 50, 70, 120 etc).

I need, for each entity, to take only the line with max date, and within that, the max of row_id.

for exmaple:

```<code>entity        date_value       row_id
50            30/06/2017       3000<br>
75            30/04/2017       2900<br>
50            30/06/2017       2890<br>
50            30/05/2017       2500<br>
50            30/06/2017       2100<br>
75            30/03/2017       2000<br>
</code>```

here I need to take only 2 rows:

```<code> 50            30/06/2017       3000<br>
 75            30/04/2017       2900<br>
</code>```

Not for all entities have rows in this table.

Can u help me with this?

Thank u.

答:
If you using Entity Framework than:

```<code>  using (var context = new YourAppConext)
  {
     var result = context.Table.GroupBy(x => x.entity).Select(y => y.OrderByDescending(z => z.date_value).ThenByDescending(t => t.row_id).FirstOrDefault()).ToList();
  }
</code>```

Idea is to have a subsets with the same entity then by using select we flatten the group then ordering set and take the data with the largest date and row id - in case of same date recordings.

Note if row_id is a string then it`s more complicated.

ContentLicense: CC BY-SA 3.0

Title: list of entity, max date, max row_id

Body:
I have table in SQLServer.

I have list in c#, of entity id. (ex: 50, 70, 120 etc).

I need, for each entity, to take only the line with max date, and within that, the max of row_id.

for exmaple:

entity        date_value       row_id
50            30/06/2017       3000

75            30/04/2017       2900

50            30/06/2017       2890

50            30/05/2017       2500

50            30/06/2017       2100

75            30/03/2017       2000

here I need to take only 2 rows:

 50            30/06/2017       3000

 75            30/04/2017       2900

Not for all entities have rows in this table.

Can u help me with this?

Thank u.

Body:
If you using Entity Framework than:

  using (var context = new YourAppConext)
  {
     var result = context.Table.GroupBy(x => x.entity).Select(y => y.OrderByDescending(z => z.date_value).ThenByDescending(t => t.row_id).FirstOrDefault()).ToList();
  }

Idea is to have a subsets with the same entity then by using select we flatten the group then ordering set and take the data with the largest date and row id - in case of same date recordings.

Note if row_id is a string then it`s more complicated.


问:
Devise nested form not creating profile
Rails 5.0.1

Devise 4.2.0

Hello, I'm building an app in which the user must fill a form to sign up, which includes the registration info for devise, and some personal info por their profile. I have made the models for user and profile, established their one to one relation, and added accept_nested_attributes_for :profile inside the user. I have also modified the registrations views to include f.fields_for for the profile, and until that point everything seems to work fine.

But, when I try to create a new user, and fill the required information, I get an error inside the view (from devise I guess) saying:

1 error prohibited this user from being saved

Profile user must exist

I have already followed many guides on how to create a nested form with devise, and none of them seem to have this issue, and I have also searched a lot with no answer. Here are some snippets from my registration controller, user and profile model, and registrations/new view:

registrations_controller

```<code>class Users::RegistrationsController < Devise::RegistrationsController
  before_action :configure_sign_up_params, only: [:create]
  before_action :configure_account_update_params, only: [:update]

  def new
    build_resources({})
    resource.build_profile
    respond_with self.resource
  end

  protected

  def configure_sign_up_params
    devise_parameter_sanitizer.permit(:sign_up,
                      keys: [:email, :password,
                      :password_confirmation,
                      profile_attributes: [:name, :art_name,
                      :birth_date, :location]])
  end
</code>```

User model

```<code>class User < ApplicationRecord
  has_one :profile, dependent: :destroy
  before_create :build_profile
  accepts_nested_attributes_for :profile

  # Devise configuration.....
end
</code>```

Profile model

```<code>class Profile < ApplicationRecord
  belongs_to :user
end
</code>```

Registrations/new view

```<code>  <h2>Nueva Cuenta</h2>
  <%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
    <%= devise_error_messages! %>

    <%= f.fields_for :profile do |b| %>

      <div class="field">
        <%= b.label :name, "Nombre" %><br />
        <%= b.text_field :name %>
      </div>

      <div class="field">
        <%= b.label :art_name, "Nombre artistico" %><br />
        <%= b.text_field :art_name %>
      </div>

      <div class="field">
        <%= b.label :birth_date, "Fecha de nacimiento" %><br />
        <%= b.date_field :birth_date %>
      </div>

      <div class="field">
        <%= b.label :location, "Ubicacion" %><br />
        <%= b.text_field :location %>
      </div>

    <% end %>

    <div class="field">
      <%= f.label :email %><br />
      <%= f.email_field :email, autofocus: true %>
    </div>

    <div class="field">
      <%= f.label :password %>
      <% if @minimum_password_length %>
        <em>(<%= @minimum_password_length %> characters minimum)</em>
      <% end %><br />
      <%= f.password_field :password, autocomplete: "off" %>
    </div>

    <div class="field">
      <%= f.label :password_confirmation %><br />
      <%= f.password_field :password_confirmation, autocomplete: "off" %>
    </div>

    <div class="actions">
      <%= f.submit "Sign up" %>
    </div>
  <% end %>

  <%= render "devise/shared/links" %>
</code>```

My guess is that it has something to do with the sanitizers, I'm not completely sure how do I pass each attribute through, since most of the guides that explained this did with an older version of devise.

Thanks for your attention.

答:
in your profile model, try this:

```belongs_to :user, optional: true```

it works for me

Title: Devise nested form not creating profile

Body:
Rails 5.0.1

Devise 4.2.0

Hello, I'm building an app in which the user must fill a form to sign up, which includes the registration info for devise, and some personal info por their profile. I have made the models for user and profile, established their one to one relation, and added accept_nested_attributes_for :profile inside the user. I have also modified the registrations views to include f.fields_for for the profile, and until that point everything seems to work fine.

But, when I try to create a new user, and fill the required information, I get an error inside the view (from devise I guess) saying:

1 error prohibited this user from being saved

Profile user must exist

I have already followed many guides on how to create a nested form with devise, and none of them seem to have this issue, and I have also searched a lot with no answer. Here are some snippets from my registration controller, user and profile model, and registrations/new view:

registrations_controller

class Users::RegistrationsController < Devise::RegistrationsController
  before_action :configure_sign_up_params, only: [:create]
  before_action :configure_account_update_params, only: [:update]

  def new
    build_resources({})
    resource.build_profile
    respond_with self.resource
  end

  protected

  def configure_sign_up_params
    devise_parameter_sanitizer.permit(:sign_up,
                      keys: [:email, :password,
                      :password_confirmation,
                      profile_attributes: [:name, :art_name,
                      :birth_date, :location]])
  end

User model

class User < ApplicationRecord
  has_one :profile, dependent: :destroy
  before_create :build_profile
  accepts_nested_attributes_for :profile

  # Devise configuration.....
end

Profile model

class Profile < ApplicationRecord
  belongs_to :user
end

Registrations/new view

Nueva Cuenta

  <%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
    <%= devise_error_messages! %>

    <%= f.fields_for :profile do |b| %>

        <%= b.label :name, "Nombre" %>

        <%= b.text_field :name %>

        <%= b.label :art_name, "Nombre artistico" %>

        <%= b.text_field :art_name %>

        <%= b.label :birth_date, "Fecha de nacimiento" %>

        <%= b.date_field :birth_date %>

        <%= b.label :location, "Ubicacion" %>

        <%= b.text_field :location %>

    <% end %>

      <%= f.label :email %>

      <%= f.email_field :email, autofocus: true %>

      <%= f.label :password %>
      <% if @minimum_password_length %>
        (<%= @minimum_password_length %> characters minimum)
      <% end %>

      <%= f.password_field :password, autocomplete: "off" %>

      <%= f.label :password_confirmation %>

      <%= f.password_field :password_confirmation, autocomplete: "off" %>

      <%= f.submit "Sign up" %>

  <% end %>

  <%= render "devise/shared/links" %>

My guess is that it has something to do with the sanitizers, I'm not completely sure how do I pass each attribute through, since most of the guides that explained this did with an older version of devise.

Thanks for your attention.

Body:
in your profile model, try this:

belongs_to :user, optional: true

it works for me


问:
Deserialize JSON object xamarin C#
I am getting the following error in Xamarin cross platform while deserializing the JSON Object. I have tried to do it with dictionary. But, everything gives me the same exception.

```<code>Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[NBStudents.Models.jsonobjectclass+User]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.Path 'data.name', line 4, position 11.
</code>```

My JSON Object Class:

```<code>public class jsonobjectclass
{
    public class User
    {
        public string name { get; set; }
        public string email { get; set; }
        public string phone { get; set; }
        public string current_group { get; set; }
        public List<UserGroups> user_groups { get; set; }
    }

    public class UserGroups
    {
        [JsonProperty("10")]
        public string Student { get; set; }
        [JsonProperty("15")]
        public string Tutor { get; set; }
        [JsonProperty("11")]
        public string Parent { get; set; }
    }

    public class Token
    {
        public string access_token { get; set; }
        public int expires_in { get; set; }
        public string token_type { get; set; }
        public string scope { get; set; }
        public string refresh_token { get; set; }
        public string error { get; set; }
    }

    public class UserResponse
    {
        public string msg { get; set; }
        public List<User> data { get; set; }
        public bool error { get; set; }
    }
}
</code>```

My Code to Deserialize JSON:

```<code>public static async Task<jsonobjectclass.UserResponse> UserRetrievalTask(string token, string apiUrl)
    {
        var jsonObject = new jsonobjectclass.UserResponse();
        string readHttpResponse;

        using (var httpClient = new HttpClient())
        {
            using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, apiUrl))
            {
                httpRequestMessage.Headers.Add("Authorization", "Bearer " + token);
                using (var httpResponse = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false))
                {
                    readHttpResponse = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    var jObject = JObject.Parse(readHttpResponse);
                    try
                    {
                        jsonObject = JsonConvert.DeserializeObject<jsonobjectclass.UserResponse>(jObject.ToString());
                    }
                    catch(Exception ex)
                    {
                        string excep = ex.ToString();
                        readHttpResponse = excep;
                    }
                }
            }
        }
        return jsonObject;
    }
</code>```

My JSON String:

```<code>{{
  "msg": null,
  "data": {
  "name": "geoit",
  "email": "rokesh@geoit.in",
  "phone": null,
  "current_group": "11",
  "user_groups": {
   "11": "Parent"
   }
},
"error": false
}}
</code>```

Please Help me to solve this.

Thanks,
Rokesh

答:
Aplogies for the misleading answer earlier. The object you need to make array is the 'data' property of the response JSON. You have to get it from the server side as your Domainmodal List<User>. You should get a better understanding from this fiddle

readHttpResponse can be

```<code>    {
          "msg": null,
          "data": [{
          "name": "geoit",
          "email": "rokesh@geoit.in",
          "phone": null,
          "current_group": "11",
          "user_groups": {
           "11": "Parent"
           }
        }],
        "error": false
   }
 and
</code>```

readHttpResponse.data needs to be array

```<code>[{
              "name": "geoit",
              "email": "rokesh@geoit.in",
              "phone": null,
              "current_group": "11",
              "user_groups": {
               "11": "Parent"
               }
            }]
</code>```

Title: Deserialize JSON object xamarin C#

Body:
I am getting the following error in Xamarin cross platform while deserializing the JSON Object. I have tried to do it with dictionary. But, everything gives me the same exception.

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[NBStudents.Models.jsonobjectclass+User]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.Path 'data.name', line 4, position 11.

My JSON Object Class:

public class jsonobjectclass
{
    public class User
    {
        public string name { get; set; }
        public string email { get; set; }
        public string phone { get; set; }
        public string current_group { get; set; }
        public List<UserGroups> user_groups { get; set; }
    }

    public class UserGroups
    {
        [JsonProperty("10")]
        public string Student { get; set; }
        [JsonProperty("15")]
        public string Tutor { get; set; }
        [JsonProperty("11")]
        public string Parent { get; set; }
    }

    public class Token
    {
        public string access_token { get; set; }
        public int expires_in { get; set; }
        public string token_type { get; set; }
        public string scope { get; set; }
        public string refresh_token { get; set; }
        public string error { get; set; }
    }

    public class UserResponse
    {
        public string msg { get; set; }
        public List<User> data { get; set; }
        public bool error { get; set; }
    }
}

My Code to Deserialize JSON:

public static async Task<jsonobjectclass.UserResponse> UserRetrievalTask(string token, string apiUrl)
    {
        var jsonObject = new jsonobjectclass.UserResponse();
        string readHttpResponse;

        using (var httpClient = new HttpClient())
        {
            using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, apiUrl))
            {
                httpRequestMessage.Headers.Add("Authorization", "Bearer " + token);
                using (var httpResponse = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false))
                {
                    readHttpResponse = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    var jObject = JObject.Parse(readHttpResponse);
                    try
                    {
                        jsonObject = JsonConvert.DeserializeObject<jsonobjectclass.UserResponse>(jObject.ToString());
                    }
                    catch(Exception ex)
                    {
                        string excep = ex.ToString();
                        readHttpResponse = excep;
                    }
                }
            }
        }
        return jsonObject;
    }

My JSON String:

{{
  "msg": null,
  "data": {
  "name": "geoit",
  "email": "rokesh@geoit.in",
  "phone": null,
  "current_group": "11",
  "user_groups": {
   "11": "Parent"
   }
},
"error": false
}}

Please Help me to solve this.

Thanks,
Rokesh

Body:
Aplogies for the misleading answer earlier. The object you need to make array is the 'data' property of the response JSON. You have to get it from the server side as your Domainmodal List<User>. You should get a better understanding from this fiddle

readHttpResponse can be

    {
          "msg": null,
          "data": [{
          "name": "geoit",
          "email": "rokesh@geoit.in",
          "phone": null,
          "current_group": "11",
          "user_groups": {
           "11": "Parent"
           }
        }],
        "error": false
   }
 and

readHttpResponse.data needs to be array

[{
              "name": "geoit",
              "email": "rokesh@geoit.in",
              "phone": null,
              "current_group": "11",
              "user_groups": {
               "11": "Parent"
               }
            }]


问:
How to replace string with fallback option?
I would like to replace string with fallback option. for example

```<code>var x = " Hello {{first_name | fallback : 'User' }} "
var f_name = "ME";
</code>```

in above case i want if f_name is defined then result will like this

```<code>Hello ME
</code>```

other wise result will be

```<code>Hello User
</code>```

so how can i do this?

答:
ES5 :

```<code>var x = "Hello " + (first_name || "User")
</code>```

ES6 :

```<code>let x = ´Hello ${first_name || "User"}´
</code>```

Edit after your new question in the comments : if you want to apply a replace or something :

```<code>var x = "Hello " + (first_name ? first_name.replace(/some.RegEx/g, '') : "User")
</code>```

Body:
I would like to replace string with fallback option. for example

var x = " Hello {{first_name | fallback : 'User' }} "
var f_name = "ME";

in above case i want if f_name is defined then result will like this

Hello ME

other wise result will be

Hello User

so how can i do this?

Body:
ES5 :

var x = "Hello " + (first_name || "User")

ES6 :

let x = ´Hello ${first_name || "User"}´

Edit after your new question in the comments : if you want to apply a replace or something :

var x = "Hello " + (first_name ? first_name.replace(/some.RegEx/g, '') : "User")


问:
Delete all text on a line after specified text is found
I am using a program called TextCrawler Pro which allows me to run as a macro.

I'd like to clean up a weather page on a daily basis to go from this:

```<code>Billings, MT;93;62;80;53;Not as warm;NNE;10;44%;20%;8

Birmingham, AL;80;70;81;69;Thunderstorms;SSW;6;81%;90%;4

Bismarck, ND;92;57;92;63;Mostly sunny;SE;12;46%;36%;8

Boise, ID;85;51;77;49;Mostly sunny, nice;N;8;36%;0%;8
</code>```

to this:

```<code>Billings, MT;93;62;80;53;

Birmingham, AL;80;70;81;69;

Bismarck, ND;92;57;92;63;

Boise, ID;85;51;77;49;
</code>```

I can find using \;\d+\;\d+\;\d+\;\d+\; but I can't delete to the end of the line.

I tried adding \r\n to the end of the above like this: \;\d+\;\d+\;\d+\;\d+\;\r\n

but that replaces all my City information with the actual regex code.

Any ideas? I feel like I'm missing something very simple.

答:
There will be many, many different patterns that will successfully remove the unwanted substrings for you.  Here are a few that I've cooked up.  (Demo)

67 steps ^([^;]+;[^;]+;[^;]+;[^;]+;[^;]+;).*$  #most efficient pattern in my list

91 steps ^((?:[^;]+;){5}).*$

127 steps (.+?;.+?;.+?;.+?;.+?;).*

157 steps ((?:.+?;){5}).*

163 steps (.+?;)[^\d].*

185 steps (.+\d{2};)[A-Z].*

280 steps (.*\,\s[A-Z]+;\d{2};\d{2};\d{2};\d{2};)(.+)

The way that you remove the unwanted part, is by replacing the full line with just the wanted part.

Referencing these document pages:

https://www.digitalvolcano.co.uk/textcrawlermanual/regular_expression_reference_guide.htm

https://www.digitalvolcano.co.uk/textcrawlermanual/regular_expression_find_replace.htm

You should be able to just use $1 as the replacement value and everything will be cleaned up.

Body:
I am using a program called TextCrawler Pro which allows me to run as a macro.

I'd like to clean up a weather page on a daily basis to go from this:

Billings, MT;93;62;80;53;Not as warm;NNE;10;44%;20%;8

Birmingham, AL;80;70;81;69;Thunderstorms;SSW;6;81%;90%;4

Bismarck, ND;92;57;92;63;Mostly sunny;SE;12;46%;36%;8

Boise, ID;85;51;77;49;Mostly sunny, nice;N;8;36%;0%;8

to this:

Billings, MT;93;62;80;53;

Birmingham, AL;80;70;81;69;

Bismarck, ND;92;57;92;63;

Boise, ID;85;51;77;49;

I can find using \;\d+\;\d+\;\d+\;\d+\; but I can't delete to the end of the line.

I tried adding \r\n to the end of the above like this: \;\d+\;\d+\;\d+\;\d+\;\r\n

but that replaces all my City information with the actual regex code.

Any ideas? I feel like I'm missing something very simple.


问:
AVMutableComposition somehow exports portrait video to landscape orientation
This function is exporting the merged composition to a landscape orientation when the source video is in portrait. I save the original video in portrait orientation to my documents directory and then save it to camera roll and works fine. I then pass the saved video's url to this function and it somehow rotates it to landscape when it shouldn't. How do I fix this?</p>

```<code>func makeVideoOverlay (url : URL) {

    print("documents directory url: \(url)")

    let composition = AVMutableComposition()
    let vidAsset = AVURLAsset(url: url as URL, options: nil)

    // get video track

    let vtrack =  vidAsset.tracks(withMediaType: AVMediaTypeVideo)
    let videoTrack:AVAssetTrack = vtrack[0]
    let vid_duration = videoTrack.timeRange.duration
    let vid_timerange = CMTimeRangeMake(kCMTimeZero, vidAsset.duration)

    //var error: NSError?

    let compositionvideoTrack:AVMutableCompositionTrack = composition.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID: CMPersistentTrackID())

    do {
        try compositionvideoTrack.insertTimeRange(vid_timerange, of: videoTrack, at: kCMTimeZero)
    } catch {
        // handle error

        print("comp video track error: \(error.localizedDescription)")
    }

    compositionvideoTrack.preferredTransform = videoTrack.preferredTransform

    let size = videoTrack.naturalSize

    //this prints out to 1920x1080 landscape dimension. i don't know how

    print("asset size: \(size)")

    // Watermark Effect

    let imglogo = UIImage(named: "logo-image")
    let imglayer = CALayer()
    imglayer.contents = imglogo?.cgImage
    imglayer.frame = CGRect.init(x: 5, y: size.height-160, width: 150, height: 150)
    imglayer.opacity = 1.0

    let videolayer = CALayer()
    videolayer.frame = CGRect.init(x: 0, y: 0, width: size.width, height:  size.height)

    let parentlayer = CALayer()
    parentlayer.frame = CGRect.init(x: 0, y: 0, width: size.width, height:  size.height)

    parentlayer.addSublayer(videolayer)
    parentlayer.addSublayer(imglayer)

    let layercomposition = AVMutableVideoComposition()
    layercomposition.frameDuration = CMTimeMake(1, 30)
    layercomposition.renderSize = size
    layercomposition.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videolayer, in: parentlayer)

    // instruction for watermark

    let instruction = AVMutableVideoCompositionInstruction()
    instruction.timeRange = CMTimeRangeMake(kCMTimeZero, composition.duration)

    let videotrack = composition.tracks(withMediaType: AVMediaTypeVideo)[0] as AVAssetTrack
    let layerinstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: videotrack)

    instruction.layerInstructions = NSArray(object: layerinstruction) as [AnyObject] as [AnyObject] as! [AVVideoCompositionLayerInstruction]

    layercomposition.instructions = NSArray(object: instruction) as [AnyObject] as [AnyObject] as! [AVVideoCompositionInstructionProtocol]

    //  create new file to receive data

    let dirPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let docsDir: String = dirPaths[0] as String

    let movieFilePath = docsDir.appending("/result.mov") as String

    movieDestinationUrl = URL(fileURLWithPath: movieFilePath)

    print("overlay destination url: \(movieDestinationUrl)")

    // use AVAssetExportSession to export video

    let assetExport = AVAssetExportSession(asset: composition, presetName:AVAssetExportPresetHighestQuality)

    assetExport?.outputFileType = AVFileTypeQuickTimeMovie
    assetExport?.outputURL = movieDestinationUrl as URL

    assetExport?.videoComposition = layercomposition

    assetExport?.exportAsynchronously(completionHandler: {

        if assetExport?.status == AVAssetExportSessionStatus.failed
        {
            print("failed: \(assetExport?.error)")
        }
        else if assetExport?.status == AVAssetExportSessionStatus.cancelled
        {
            print("cancelled: \(assetExport?.error)")
        }
        else
        {
            print("Movie complete")

            OperationQueue.main.addOperation({ () -> Void in

                //saves in landscape
                self.saveAsset(url: self.movieDestinationUrl)
            })
        }
    })
}
</code>```

答:
AVMutableVideoCompositionLayerInstruction has a method setTransform(_:at:)

As documentation say

Sets a fixed transform to apply from the specified time until the next
  time at which a transform is set. [...]. Before the first specified time for which a
  transform is set, the affine transform is held constant at the value
  of  identity ; after the last time for which a transform is set, the
  affine transform is held constant at that last value.

You should set videoTrack's preferredTransform to layerInstruction instead.

EDIT

You need to create layerinstruction with the new created composition track instead.

let layerinstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: compositionvideoTrack) // NOT videoTrack.
layerinstruction.setTransform(videoTrack.preferredTransform, at: kCMTimeZero)

Body:
This function is exporting the merged composition to a landscape orientation when the source video is in portrait. I save the original video in portrait orientation to my documents directory and then save it to camera roll and works fine. I then pass the saved video's url to this function and it somehow rotates it to landscape when it shouldn't. How do I fix this?

func makeVideoOverlay (url : URL) {

    print("documents directory url: \(url)")

    let composition = AVMutableComposition()
    let vidAsset = AVURLAsset(url: url as URL, options: nil)

    // get video track

    let vtrack =  vidAsset.tracks(withMediaType: AVMediaTypeVideo)
    let videoTrack:AVAssetTrack = vtrack[0]
    let vid_duration = videoTrack.timeRange.duration
    let vid_timerange = CMTimeRangeMake(kCMTimeZero, vidAsset.duration)

    //var error: NSError?

    let compositionvideoTrack:AVMutableCompositionTrack = composition.addMutableTrack(withMediaType: AVMediaTypeVideo, preferredTrackID: CMPersistentTrackID())

    do {
        try compositionvideoTrack.insertTimeRange(vid_timerange, of: videoTrack, at: kCMTimeZero)
    } catch {
        // handle error

        print("comp video track error: \(error.localizedDescription)")
    }

    compositionvideoTrack.preferredTransform = videoTrack.preferredTransform

    let size = videoTrack.naturalSize

    //this prints out to 1920x1080 landscape dimension. i don't know how

    print("asset size: \(size)")

    // Watermark Effect

    let imglogo = UIImage(named: "logo-image")
    let imglayer = CALayer()
    imglayer.contents = imglogo?.cgImage
    imglayer.frame = CGRect.init(x: 5, y: size.height-160, width: 150, height: 150)
    imglayer.opacity = 1.0

    let videolayer = CALayer()
    videolayer.frame = CGRect.init(x: 0, y: 0, width: size.width, height:  size.height)

    let parentlayer = CALayer()
    parentlayer.frame = CGRect.init(x: 0, y: 0, width: size.width, height:  size.height)

    parentlayer.addSublayer(videolayer)
    parentlayer.addSublayer(imglayer)

    let layercomposition = AVMutableVideoComposition()
    layercomposition.frameDuration = CMTimeMake(1, 30)
    layercomposition.renderSize = size
    layercomposition.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videolayer, in: parentlayer)

    // instruction for watermark

    let instruction = AVMutableVideoCompositionInstruction()
    instruction.timeRange = CMTimeRangeMake(kCMTimeZero, composition.duration)

    let videotrack = composition.tracks(withMediaType: AVMediaTypeVideo)[0] as AVAssetTrack
    let layerinstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: videotrack)

    instruction.layerInstructions = NSArray(object: layerinstruction) as [AnyObject] as [AnyObject] as! [AVVideoCompositionLayerInstruction]

    layercomposition.instructions = NSArray(object: instruction) as [AnyObject] as [AnyObject] as! [AVVideoCompositionInstructionProtocol]

    //  create new file to receive data

    let dirPaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
    let docsDir: String = dirPaths[0] as String

    let movieFilePath = docsDir.appending("/result.mov") as String

    movieDestinationUrl = URL(fileURLWithPath: movieFilePath)

    print("overlay destination url: \(movieDestinationUrl)")

    // use AVAssetExportSession to export video

    let assetExport = AVAssetExportSession(asset: composition, presetName:AVAssetExportPresetHighestQuality)

    assetExport?.outputFileType = AVFileTypeQuickTimeMovie
    assetExport?.outputURL = movieDestinationUrl as URL

    assetExport?.videoComposition = layercomposition

    assetExport?.exportAsynchronously(completionHandler: {

        if assetExport?.status == AVAssetExportSessionStatus.failed
        {
            print("failed: \(assetExport?.error)")
        }
        else if assetExport?.status == AVAssetExportSessionStatus.cancelled
        {
            print("cancelled: \(assetExport?.error)")
        }
        else
        {
            print("Movie complete")

            OperationQueue.main.addOperation({ () -> Void in

                //saves in landscape
                self.saveAsset(url: self.movieDestinationUrl)
            })
        }
    })
}


问:
RegEx question - HTML tag content
I want to replace all "i" character in  with "I" by JavaScript.
(for example:
Hi! it!
 should change to
HI! It!
).
I know I must use regular expressions. but I don't know what I should write.
Can you help me?
Thanks ..

答:
Here's an alternative, using CSS, jQuery and a Highlight plugin:

CSS:

```<code>.highlight {text-transform:uppercase;}
</code>```

JavaScript:

```<code>$('body').highlight('i');
</code>```

Working example: http://jsbin.com/okavo4

This is a quick example, but you can use the source code to get what you want, in case you need something more complex. Using a regular expression on the source of your body is wrong, specially in context of a browser, where you already have a parsed DOM structure.

ContentLicense: CC BY-SA 2.5

Title: RegEx question - HTML tag content

Body:
Here's an alternative, using CSS, jQuery and a Highlight plugin:

CSS:

.highlight {text-transform:uppercase;}

JavaScript:

$('body').highlight('i');

Working example: http://jsbin.com/okavo4

This is a quick example, but you can use the source code to get what you want, in case you need something more complex. Using a regular expression on the source of your body is wrong, specially in context of a browser, where you already have a parsed DOM structure.


答:
When you instruct Cloudant to create an index from the fields "sortdate","coordinates", it creates an data structure on disk ordered by sortdate and coordinates. If you subsequently perform a query that can be optimised using this index then your query will be get a performance boost.

Unfortunately, the query you are making is not helped by the index you created. Querying by coordinates on its own is helped by an index on sortdate & coordinates.

Your query may be boosted by an index on coordinates on its own e.g.

```<code>{
  "index": {
    "fields": [

        "sortdate","coordinates"
            ]
      },
    "type": "json"
}
</code>```

Title: sorting not working as expected in ibm bluemix node red environment

Body:
I have created index using this post request
payload :

{
  "index": {
    "fields": [

        "sortdate","coordinates"
            ]
      },
    "type": "json"
  }

and index created successfully.
Now i fetch the record using this post request
URL

Payload:

{
  "selector": {
    "coordinates": [18.497484,73.81349]
  },
   "sort": [
    {
      "sortdate": "asc"
    }
  ]
}

and getting following response:

{
    "warning": "no matching index found, create an index to optimize query time",
    "docs": [
        {
            "_id": "4254f2d4638806b54802144ff25ecba7",
            "_rev": "1-6d3d573f21eb6d6518093aeb36a3ed5f",
            "aqi": 26,
            "coordinates": [
                18.497484,
                73.81349
            ],
            "so2": {
                "avg": 10,
                "aqi": 12
            },
            "pm10": {
                "avg": 26,
                "aqi": 26
            },
            "pm25": {
                "avg": 13,
                "aqi": 21
            },
            "date": "2017-06-30T11:08:45.439Z",
            "sortdate": 1498820925439
        },
        {
            "_id": "7c0278d8dfb3182c54ee1d6b03839b74",
            "_rev": "1-09d2b1354177f306b859f7f8c33d65d1",
            "aqi": 25,
            "coordinates": [
                18.497484,
                73.81349
            ],
            "so2": {
                "avg": 9,
                "aqi": 11
            },
            "pm10": {
                "avg": 25,
                "aqi": 25
            },
            "pm25": {
                "avg": 14,
                "aqi": 23
            },
            "date": "2017-06-30T09:56:55.004Z",
            "sortdate": 1498816615004
        },
        {
            "_id": "98e28cd2012a7c1b922f944162d12e00",
            "_rev": "1-b62d7c5fee4c9c9699cb7a9f950ec62c",
            "aqi": 25,
            "coordinates": [
                18.497484,
                73.81349
            ],
            "so2": {
                "avg": 9,
                "aqi": 11
            },
            "pm10": {
                "avg": 25,
                "aqi": 25
            },
            "pm25": {
                "avg": 14,
                "aqi": 23
            },
            "date": "2017-06-30T10:23:22.896Z",
            "sortdate": 1498818202896
        },
        {
            "_id": "cb6f3d1a313df7e95326d13085b480c9",
            "_rev": "1-77678d8df1c04dfc33f513906a97ca1e",
            "aqi": 26,
            "coordinates": [
                18.497484,
                73.81349
            ],
            "so2": {
                "avg": 10,
                "aqi": 12
            },
            "pm10": {
                "avg": 26,
                "aqi": 26
            },
            "pm25": {
                "avg": 13,
                "aqi": 21
            },
            "date": "2017-06-30T11:08:05.364Z",
            "sortdate": 1498820885364
        },
        {
            "_id": "db1fe2e2403f8acd8655a3a65cf4b36c",
            "_rev": "1-ef51370ef1ddc7215512b4644d095634",
            "aqi": 25,
            "coordinates": [
                18.497484,
                73.81349
            ],
            "so2": {
                "avg": 9,
                "aqi": 11
            },
            "pm10": {
                "avg": 25,
                "aqi": 25
            },
            "pm25": {
                "avg": 14,
                "aqi": 23
            },
            "date": "2017-06-30T09:42:40.284Z",
            "sortdate": 1498815760284
        },
        {
            "_id": "e226e828bce5e31534db87f44f98efae",
            "_rev": "1-2a238373a47575158866c56019d75fbe",
            "aqi": 25,
            "coordinates": [
                18.497484,
                73.81349
            ],
            "so2": {
                "avg": 9,
                "aqi": 11
            },
            "pm10": {
                "avg": 25,
                "aqi": 25
            },
            "pm25": {
                "avg": 14,
                "aqi": 23
            },
            "date": "2017-06-30T09:43:18.894Z",
            "sortdate": 1498815798894
        },
        {
            "_id": "e38663621c6148952fd84e3ab54195c0",
            "_rev": "1-fa45393376d7dc8677ebd48bd2804d70",
            "aqi": 26,
            "coordinates": [
                18.497484,
                73.81349
            ],
            "so2": {
                "avg": 10,
                "aqi": 12
            },
            "pm10": {
                "avg": 26,
                "aqi": 26
            },
            "pm25": {
                "avg": 14,
                "aqi": 23
            },
            "date": "2017-06-30T10:25:17.277Z",
            "sortdate": 1498818317277
        },
        {
            "_id": "e435e43de6bcb01c1596874afacef581",
            "_rev": "1-072be28b4128118e443c500494f456a1",
            "aqi": 26,
            "coordinates": [
                18.497484,
                73.81349
            ],
            "so2": {
                "avg": 10,
                "aqi": 12
            },
            "pm10": {
                "avg": 26,
                "aqi": 26
            },
            "pm25": {
                "avg": 13,
                "aqi": 21
            },
            "date": "2017-06-30T11:59:21.235Z",
            "sortdate": 1498823961235
        },
        {
            "_id": "f195832354b6fc816e1039dacf41546f",
            "_rev": "1-52fa322d3c034ddf70259991ac7c7021",
            "aqi": 26,
            "coordinates": [
                18.497484,
                73.81349
            ],
            "so2": {
                "avg": 10,
                "aqi": 12
            },
            "pm10": {
                "avg": 26,
                "aqi": 26
            },
            "pm25": {
                "avg": 14,
                "aqi": 23
            },
            "date": "2017-06-30T10:24:01.539Z",
            "sortdate": 1498818241539
        }
    ]
}

As you can see  record are not coming sorted as per sortdate field.

I am not getting what is wrong here.

Body:
When you instruct Cloudant to create an index from the fields "sortdate","coordinates", it creates an data structure on disk ordered by sortdate and coordinates. If you subsequently perform a query that can be optimised using this index then your query will be get a performance boost.

Unfortunately, the query you are making is not helped by the index you created. Querying by coordinates on its own is helped by an index on sortdate & coordinates.

Your query may be boosted by an index on coordinates on its own e.g.

{
  "index": {
    "fields": [

        "sortdate","coordinates"
            ]
      },
    "type": "json"
}


问:
Is there any way to add my custom POIs on maps?
I have a lot of POIs in my database including location property. How can I add those POIs based on my location on my Map? I found HERE SDK has api like 'Explore Popular Places by Category', but these categories are predefined by HERE. I don't think I can add my POIs to HERE and search by these APIs.

I knew a solution that by adding cluster Marker on Map. but It's difficult and expensive if I retrieve POIs in my database every time. like finding all the POIs which within a circle region(radius is 10 miles). Do you have any better solution for adding custom POIs on HERE map?

Thanks

答:
You can add your custom POIs(markers) with custom images using HERE maps, here is the code:

After initialisation map onButtonClick,

```<code>SearchRequest searchRequest = new SearchRequest("Water");
searchRequest.execute(discoveryResultPageListener);
</code>```

then add this method:

```<code>private ResultListener<DiscoveryResultPage> discoveryResultPageListener = new ResultListener<DiscoveryResultPage>() {
    @Override
    public void onCompleted(DiscoveryResultPage discoveryResultPage, ErrorCode errorCode) {

        if (errorCode == ErrorCode.NONE) {

            List<DiscoveryResult> s_ResultList = discoveryResultPage.getItems();
            for (DiscoveryResult item : s_ResultList) {
                /*
                 * Add a marker for each result of PlaceLink type.For best usability, map can be
                 * also adjusted to display all markers.This can be done by merging the bounding
                 * box of each result and then zoom the map to the merged one.
                 */
                if (item.getResultType() == DiscoveryResult.ResultType.PLACE) {
                    PlaceLink placeLink = (PlaceLink) item;
                    addMarkerAtPlace(placeLink);
                    Log.e("nameeee   ",""+placeLink.getTitle());
                }
            }
        } else {
            Toast.makeText(m_activity,
                    "ERROR:Discovery search request returned return error code+ " + errorCode,
                    Toast.LENGTH_SHORT).show();
        }
    }
};
</code>```

after this add a method for custom marker,

```<code>private void addMarkerAtPlace(PlaceLink placeLink) {
    Image img = new Image();
    try {
        img.setImageResource(R.drawable.camping);

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

    MapMarker mapMarker = new MapMarker();
    mapMarker.setIcon(img);
    mapMarker.setTitle(placeLink.getTitle());
    mapMarker.setCoordinate(new GeoCoordinate(placeLink.getPosition()));
    m_map.addMapObject(mapMarker);
    m_map.setCenter(new GeoCoordinate(placeLink.getPosition()), Map.Animation.NONE);

    m_map.setZoomLevel(13);
    List<MapObject> m_mapObjectList = new ArrayList<>();
    m_mapObjectList.add(mapMarker);
}
</code>```

Body:
You can add your custom POIs(markers) with custom images using HERE maps, here is the code:

After initialisation map onButtonClick,

SearchRequest searchRequest = new SearchRequest("Water");
searchRequest.execute(discoveryResultPageListener);

then add this method:

private ResultListener<DiscoveryResultPage> discoveryResultPageListener = new ResultListener<DiscoveryResultPage>() {
    @Override
    public void onCompleted(DiscoveryResultPage discoveryResultPage, ErrorCode errorCode) {

        if (errorCode == ErrorCode.NONE) {

            List<DiscoveryResult> s_ResultList = discoveryResultPage.getItems();
            for (DiscoveryResult item : s_ResultList) {
                /*
                 * Add a marker for each result of PlaceLink type.For best usability, map can be
                 * also adjusted to display all markers.This can be done by merging the bounding
                 * box of each result and then zoom the map to the merged one.
                 */
                if (item.getResultType() == DiscoveryResult.ResultType.PLACE) {
                    PlaceLink placeLink = (PlaceLink) item;
                    addMarkerAtPlace(placeLink);
                    Log.e("nameeee   ",""+placeLink.getTitle());
                }
            }
        } else {
            Toast.makeText(m_activity,
                    "ERROR:Discovery search request returned return error code+ " + errorCode,
                    Toast.LENGTH_SHORT).show();
        }
    }
};

after this add a method for custom marker,

private void addMarkerAtPlace(PlaceLink placeLink) {
    Image img = new Image();
    try {
        img.setImageResource(R.drawable.camping);

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

    MapMarker mapMarker = new MapMarker();
    mapMarker.setIcon(img);
    mapMarker.setTitle(placeLink.getTitle());
    mapMarker.setCoordinate(new GeoCoordinate(placeLink.getPosition()));
    m_map.addMapObject(mapMarker);
    m_map.setCenter(new GeoCoordinate(placeLink.getPosition()), Map.Animation.NONE);

    m_map.setZoomLevel(13);
    List<MapObject> m_mapObjectList = new ArrayList<>();
    m_mapObjectList.add(mapMarker);
}


问:
Eclipse not showing run as maven test when right click on maven project
I have created a maven project through Eclipse and added all dependency's and plugins to pom.xml file. Now, I have created a package as "com.Qedge" under "src/test/java" folder then,created a class under com.Qedge package with a piece of code written using JAVA. when I right click on project to run as "maven Test", Eclipse not showing the option in run. I could able to see the same option when i right click on pom.xml file of the project.

I am new to Maven, I would like to know is there any specific reason for this behavior? What am I supposed to do to get the same option from Project folder (I.e Right click on project - Run as - Maven Test).

Please find my pom.xml file below.

```<code>    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.Qedge</groupId>
  <artifactId>MavenProjectDemo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>MavenProjectDemo</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
       <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>2.53.1</version>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.11</version>
            <scope>test</scope>
       </dependency>
       <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.16</version>
            <scope>test</scope>
       </dependency>
    </dependencies>

<build>
    <pluginManagement>
        <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.6.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.17</version>
            <inherited>true</inherited>
                <configuration>
                     <suiteXmlFiles>
                        <suiteXmlFile>testng.xml</suiteXmlFile>
                     </suiteXmlFiles>
                </configuration>
        </plugin>
        </plugins>
    </pluginManagement>
</build>
</project>
</code>```

答:
Do a right click on your project Mark as Deployable.
After it would be ok.

Body:
I have created a maven project through Eclipse and added all dependency's and plugins to pom.xml file. Now, I have created a package as "com.Qedge" under "src/test/java" folder then,created a class under com.Qedge package with a piece of code written using JAVA. when I right click on project to run as "maven Test", Eclipse not showing the option in run. I could able to see the same option when i right click on pom.xml file of the project.

I am new to Maven, I would like to know is there any specific reason for this behavior? What am I supposed to do to get the same option from Project folder (I.e Right click on project - Run as - Maven Test).

Please find my pom.xml file below.

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.Qedge</groupId>
  <artifactId>MavenProjectDemo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>MavenProjectDemo</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
       <dependency>
            <groupId>org.seleniumhq.selenium</groupId>
            <artifactId>selenium-java</artifactId>
            <version>2.53.1</version>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.11</version>
            <scope>test</scope>
       </dependency>
       <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.16</version>
            <scope>test</scope>
       </dependency>
    </dependencies>

<build>
    <pluginManagement>
        <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.6.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                </configuration>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.17</version>
            <inherited>true</inherited>
                <configuration>
                     <suiteXmlFiles>
                        <suiteXmlFile>testng.xml</suiteXmlFile>
                     </suiteXmlFiles>
                </configuration>
        </plugin>
        </plugins>
    </pluginManagement>
</build>
</project>


问:
Converting dictionary to data frame in python
First thing my loop is not working the way I want. It is giving links inside dictionary for a particular website step by step. I want to fill it at once.My output is like:

```<code>{'Banks – Assets': {'link': 'https://data.gov.au/dataset/banks-assets'}, 'Consolidated Exposures – Immediate and Ultimate Risk Basis': {}, 'Foreign Exchange Transactions and Holdings of Official Reserve Assets': {}, 'Finance Companies and General Financiers – Selected Assets and Liabilities': {}, 'Liabilities and Assets – Monthly': {}, 'Consolidated Exposures – Immediate Risk Basis – International Claims by Country': {}, 'Consolidated Exposures – Ultimate Risk Basis': {}, 'Banks – Consolidated Group off-balance Sheet Business': {}, 'Liabilities of Australian-located Operations': {}, 'Building Societies – Selected Assets and Liabilities': {}, 'Consolidated Exposures – Immediate Risk Basis – Foreign Claims by Country': {}, 'Banks – Consolidated Group Impaired Assets': {}, 'Assets and Liabilities of Australian-Located Operations': {}, 'Managed Funds': {}, 'Daily Net Foreign Exchange Transactions': {}, 'Consolidated Exposures-Immediate Risk Basis': {}, 'Public Unit Trust': {}, 'Securitisation Vehicles': {}, 'Assets of Australian-located Operations': {}, 'Banks – Consolidated Group Capital': {}}
{'Banks – Assets': {'link': 'https://data.gov.au/dataset/banks-assets'}, 'Consolidated Exposures – Immediate and Ultimate Risk Basis': {'link': 'https://data.gov.au/dataset/consolidated-exposures-immediate-and-ultimate-risk-basis'}, 'Foreign Exchange Transactions and Holdings of Official Reserve Assets': {}, 'Finance Companies and General Financiers – Selected Assets and Liabilities': {}, 'Liabilities and Assets – Monthly': {}, 'Consolidated Exposures – Immediate Risk Basis – International Claims by Country': {}, 'Consolidated Exposures – Ultimate Risk Basis': {}, 'Banks – Consolidated Group off-balance Sheet Business': {}, 'Liabilities of Australian-located Operations': {}, 'Building Societies – Selected Assets and Liabilities': {}, 'Consolidated Exposures – Immediate Risk Basis – Foreign Claims by Country': {}, 'Banks – Consolidated Group Impaired Assets': {}, 'Assets and Liabilities of Australian-Located Operations': {}, 'Managed Funds': {}, 'Daily Net Foreign Exchange Transactions': {}, 'Consolidated Exposures-Immediate Risk Basis': {}, 'Public Unit Trust': {}, 'Securitisation Vehicles': {}, 'Assets of Australian-located Operations': {}, 'Banks – Consolidated Group Capital': {}}
</code>```

Second thing I want to make data frame out of it like:

```<code>Titles                                                  Links
Banks - Assets                      https://data.gov.au/dataset/banks-assets
Consolidated Exposures – Immediate and Ultimate Risk Basis   https://data.gov.au/dataset/consolidated-exposures-immediate-and-ultimate-risk-basis
</code>```

and so on ...
My code is:

```<code>webpage4_urls = ["https://data.gov.au/dataset?q=&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&organization=departmentofagriculturefisheriesandforestry&_groups_limit=0",
                 "https://data.gov.au/dataset?q=&organization=commonwealthscientificandindustrialresearchorganisation&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&_groups_limit=0",
                 "https://data.gov.au/dataset?q=&organization=bureauofmeteorology&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&_groups_limit=0",
                 "https://data.gov.au/dataset?q=&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&organization=tasmanianmuseumandartgallery&_groups_limit=0",
                 "https://data.gov.au/dataset?q=&organization=department-of-industry&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&_groups_limit=0"]
for i in webpage4_urls:
    wiki2 = i
    page= urllib.request.urlopen(wiki2)
    soup = BeautifulSoup(page)

    lobbying = {}
    data2 = soup.find_all('h3', class_="dataset-heading")
    for element in data2:
        lobbying[element.a.get_text()] = {}
    data2[0].a["href"]
    prefix = "https://data.gov.au"
    for element in data2:
        lobbying[element.a.get_text()]["link"] = prefix + element.a["href"]
        print(lobbying)
</code>```

答:
I think you need DataFrame.from_dict + DataFrame.rename_axis + DataFrame.reset_index:

```<code>for element in data2:
    lobbying[element.a.get_text()]["link"] = prefix + element.a["href"]
    #print(lobbying)
    df = pd.DataFrame.from_dict(lobbying, orient='index').rename_axis('Titles').reset_index()
    print (df)
</code>```

EDIT:

```<code>dfs = []
for i in webpage4_urls:
    wiki2 = i
    page= urllib.request.urlopen(wiki2)
    soup = BeautifulSoup(page)

    lobbying = {}
    data2 = soup.find_all('h3', class_="dataset-heading")
    for element in data2:
        lobbying[element.a.get_text()] = {}
    data2[0].a["href"]
    prefix = "https://data.gov.au"
    for element in data2:
        print ()
        lobbying[element.a.get_text()]["link"] = prefix + element.a["href"]
        #print(lobbying)
        df = pd.DataFrame.from_dict(lobbying, orient='index').rename_axis('Titles').reset_index()
        dfs.append(df)

df = pd.concat(dfs, ignore_index=True)
print (df)
df.to_csv('output.csv')
</code>```

Body:
First thing my loop is not working the way I want. It is giving links inside dictionary for a particular website step by step. I want to fill it at once.My output is like:

{'Banks – Assets': {'link': 'https://data.gov.au/dataset/banks-assets'}, 'Consolidated Exposures – Immediate and Ultimate Risk Basis': {}, 'Foreign Exchange Transactions and Holdings of Official Reserve Assets': {}, 'Finance Companies and General Financiers – Selected Assets and Liabilities': {}, 'Liabilities and Assets – Monthly': {}, 'Consolidated Exposures – Immediate Risk Basis – International Claims by Country': {}, 'Consolidated Exposures – Ultimate Risk Basis': {}, 'Banks – Consolidated Group off-balance Sheet Business': {}, 'Liabilities of Australian-located Operations': {}, 'Building Societies – Selected Assets and Liabilities': {}, 'Consolidated Exposures – Immediate Risk Basis – Foreign Claims by Country': {}, 'Banks – Consolidated Group Impaired Assets': {}, 'Assets and Liabilities of Australian-Located Operations': {}, 'Managed Funds': {}, 'Daily Net Foreign Exchange Transactions': {}, 'Consolidated Exposures-Immediate Risk Basis': {}, 'Public Unit Trust': {}, 'Securitisation Vehicles': {}, 'Assets of Australian-located Operations': {}, 'Banks – Consolidated Group Capital': {}}
{'Banks – Assets': {'link': 'https://data.gov.au/dataset/banks-assets'}, 'Consolidated Exposures – Immediate and Ultimate Risk Basis': {'link': 'https://data.gov.au/dataset/consolidated-exposures-immediate-and-ultimate-risk-basis'}, 'Foreign Exchange Transactions and Holdings of Official Reserve Assets': {}, 'Finance Companies and General Financiers – Selected Assets and Liabilities': {}, 'Liabilities and Assets – Monthly': {}, 'Consolidated Exposures – Immediate Risk Basis – International Claims by Country': {}, 'Consolidated Exposures – Ultimate Risk Basis': {}, 'Banks – Consolidated Group off-balance Sheet Business': {}, 'Liabilities of Australian-located Operations': {}, 'Building Societies – Selected Assets and Liabilities': {}, 'Consolidated Exposures – Immediate Risk Basis – Foreign Claims by Country': {}, 'Banks – Consolidated Group Impaired Assets': {}, 'Assets and Liabilities of Australian-Located Operations': {}, 'Managed Funds': {}, 'Daily Net Foreign Exchange Transactions': {}, 'Consolidated Exposures-Immediate Risk Basis': {}, 'Public Unit Trust': {}, 'Securitisation Vehicles': {}, 'Assets of Australian-located Operations': {}, 'Banks – Consolidated Group Capital': {}}

Second thing I want to make data frame out of it like:

Titles                                                  Links
Banks - Assets                      https://data.gov.au/dataset/banks-assets
Consolidated Exposures – Immediate and Ultimate Risk Basis   https://data.gov.au/dataset/consolidated-exposures-immediate-and-ultimate-risk-basis

and so on ...
My code is:

webpage4_urls = ["https://data.gov.au/dataset?q=&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&organization=departmentofagriculturefisheriesandforestry&_groups_limit=0",
                 "https://data.gov.au/dataset?q=&organization=commonwealthscientificandindustrialresearchorganisation&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&_groups_limit=0",
                 "https://data.gov.au/dataset?q=&organization=bureauofmeteorology&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&_groups_limit=0",
                 "https://data.gov.au/dataset?q=&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&organization=tasmanianmuseumandartgallery&_groups_limit=0",
                 "https://data.gov.au/dataset?q=&organization=department-of-industry&sort=extras_harvest_portal+asc%2C+score+desc%2C+metadata_modified+desc&_organization_limit=0&groups=sciences&_groups_limit=0"]
for i in webpage4_urls:
    wiki2 = i
    page= urllib.request.urlopen(wiki2)
    soup = BeautifulSoup(page)

    lobbying = {}
    data2 = soup.find_all('h3', class_="dataset-heading")
    for element in data2:
        lobbying[element.a.get_text()] = {}
    data2[0].a["href"]
    prefix = "https://data.gov.au"
    for element in data2:
        lobbying[element.a.get_text()]["link"] = prefix + element.a["href"]
        print(lobbying)

Body:
I think you need DataFrame.from_dict + DataFrame.rename_axis + DataFrame.reset_index:

for element in data2:
    lobbying[element.a.get_text()]["link"] = prefix + element.a["href"]
    #print(lobbying)
    df = pd.DataFrame.from_dict(lobbying, orient='index').rename_axis('Titles').reset_index()
    print (df)

EDIT:

dfs = []
for i in webpage4_urls:
    wiki2 = i
    page= urllib.request.urlopen(wiki2)
    soup = BeautifulSoup(page)

    lobbying = {}
    data2 = soup.find_all('h3', class_="dataset-heading")
    for element in data2:
        lobbying[element.a.get_text()] = {}
    data2[0].a["href"]
    prefix = "https://data.gov.au"
    for element in data2:
        print ()
        lobbying[element.a.get_text()]["link"] = prefix + element.a["href"]
        #print(lobbying)
        df = pd.DataFrame.from_dict(lobbying, orient='index').rename_axis('Titles').reset_index()
        dfs.append(df)

df = pd.concat(dfs, ignore_index=True)
print (df)
df.to_csv('output.csv')


问:
How can I use SSL through Apache with multiple Tomcat Webapp instances?
We currently have our webapp which is a standard sort of thing, http main and info pages but redirects to httpS (ie SSL) for login and user actions etc.

Currently we have all our webapp instances (production, test, demo etc) deployed into one instance of Jetty and we can access them all via www.ourapp.com/test and www.ourapp.com/demo and obviously www.ourapp.com for production.

The problem with this is every time we make changes to one instance we need to restart all instances, not ideal. Also I don't particularly like using Jetty for production, even tho our app isn't very high volume at the moment.

I'm trying to move to Apache httpd forwarding to multiple instances of tomcat each hosting a different instance of our app. This would let me shutdown and restart each tomcat/app instance individually.

I have setup mutliple tomcats installations on various different ports so they don't conflict with eachother (eg 8081, 8082, 8083), set their AJP connector ports to be different to eachother (eg 8010, 8011, 8012) and httpd listens on port 8090 at the moment so as not to conflict with out current production instance running on port 80.

In the httpd.conf I have settings such as ;

JkMount /test* tomcatTest

And in workers.properties I have settings such as;

worker.tomcatTest.port=8010

worker.tomcatTest.host=localhost

worker.tomcatTest.type=ajp13

worker.tomcatTest.lbfactor=100

httpd is forwarding fine to the initial landing pages. The issues arise when I need to go to the SSL pages for login etc. Each of the tomcat installs have their SSL connector uncommented and the port varies also, 8444, 8445, 8446 etc.

Hopefully you can see the setup I'm trying to achieve here. I just need some help getting the non-SSL pages to link to the SSL pages like they normally do if they were all in one Jetty/Tomcat instance and Apache wasn't doing all the forwarding. Any pointers one what I need to do here?

答:
Suppose your worker.properties file contains this.

```<code>> worker.list=balancer,stat   worker.tomcat1.type=ajp13
> worker.tomcat1.port=8109 worker.tomcat1.host=localhost
> worker.tomcat2.type=ajp13 worker.tomcat2.port=8209
> worker.tomcat2.host=localhost   worker.tomcat3.type=ajp13
> worker.tomcat3.port=8309 worker.tomcat3.host=localhost
>     worker.balancer.type=lb worker.balancer.balance_workers=tomcat1,tomcat2,tomcat3
> worker.stat.type=status
</code>```

Then you have to add
JkMount /* balancer

in httpd-ssl.conf within the

<Virtualhost>
  tag

```<code><VirtualHost _default_:443>
#No change in other existing code
JkMount  /*  balancer

> </VirtualHost>
</code>```

Body:
Suppose your worker.properties file contains this.

> worker.list=balancer,stat   worker.tomcat1.type=ajp13
> worker.tomcat1.port=8109 worker.tomcat1.host=localhost
> worker.tomcat2.type=ajp13 worker.tomcat2.port=8209
> worker.tomcat2.host=localhost   worker.tomcat3.type=ajp13
> worker.tomcat3.port=8309 worker.tomcat3.host=localhost
>     worker.balancer.type=lb worker.balancer.balance_workers=tomcat1,tomcat2,tomcat3
> worker.stat.type=status

Then you have to add
JkMount /* balancer

in httpd-ssl.conf within the

<Virtualhost>
  tag

<VirtualHost _default_:443>
#No change in other existing code
JkMount  /*  balancer

> </VirtualHost>


问:
What's the magic of arrays in C#
```<code>int[] a = new int[5];
string[] b = new string[1];
</code>```

The types of both a and b inherit from the abstract System.Array, but there is no real classes in the built-in library(it seems that there are some runtime types, you can't find the type defination class of an int[]). Can you tell me what happens while compiling? And why did they(the c# team) make this design(I mean why it's not something like Array<T>,instead they are using an abstract class with compiler magics)?

答:
[] is a syntax(syntatic sugar) for defining Arrays in c#. Maybe CreateInstance will be replaced at runtime

```<code> Array a = Array.CreateInstance(typeof(int), 5);
</code>```

is same as

```<code>int[] a = new int[5];
</code>```

Source for CreateInstance (taken from reflector)

```<code>public static unsafe Array CreateInstance(Type elementType, int length)
{
    if (elementType == null)
    {
        throw new ArgumentNullException("elementType");
    }
    RuntimeType underlyingSystemType = elementType.UnderlyingSystemType as RuntimeType;
    if (underlyingSystemType == null)
    {
        throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "elementType");
    }
    if (length < 0)
    {
        throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
    }
    return InternalCreate((void*) underlyingSystemType.TypeHandle.Value, 1, &length, null);
}
</code>```

Title: What's the magic of arrays in C#

Body:
int[] a = new int[5];
string[] b = new string[1];

The types of both a and b inherit from the abstract System.Array, but there is no real classes in the built-in library(it seems that there are some runtime types, you can't find the type defination class of an int[]). Can you tell me what happens while compiling? And why did they(the c# team) make this design(I mean why it's not something like Array<T>,instead they are using an abstract class with compiler magics)?

Body:
[] is a syntax(syntatic sugar) for defining Arrays in c#. Maybe CreateInstance will be replaced at runtime

 Array a = Array.CreateInstance(typeof(int), 5);

is same as

int[] a = new int[5];

Source for CreateInstance (taken from reflector)

public static unsafe Array CreateInstance(Type elementType, int length)
{
    if (elementType == null)
    {
        throw new ArgumentNullException("elementType");
    }
    RuntimeType underlyingSystemType = elementType.UnderlyingSystemType as RuntimeType;
    if (underlyingSystemType == null)
    {
        throw new ArgumentException(Environment.GetResourceString("Arg_MustBeType"), "elementType");
    }
    if (length < 0)
    {
        throw new ArgumentOutOfRangeException("length", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
    }
    return InternalCreate((void*) underlyingSystemType.TypeHandle.Value, 1, &length, null);
}


问:
SSH connect from local windows VM to Azure windows VM
I want to have a SSH connection from my local windows machine or VM on my computer to Azure windows server VM. I tried Cygwin and Putty but both of them gave timeout connection. I used public ip address and opened port 22 on Azure VM.
I will appreciate if some one can give me any hints or links.</p>

答: Thanks for suggestions, I found the problem which was the host machine IP address(ipconfig) (where is a local VM inside domain) was different from the IP address that communicate outside the domain to internet. I was set in NSG of Azure VM to only accept this IP and because of that it gave time-out error. After changing the IP it works.</p>


问:
Kubernetes Job: exactly one pod
I want to run only one pod of my kubernetes app at a time(relaunch in case of failure), I am using job controller.

But as per documentations, kubernetes may launch more than one pods and will eventually achieve specified replicas. Is there any way to achieve exactly one pod at a time or any recommended design pattern for such use cases.

My app is reading data from HDFS and writing it to a message queue. It exits after processing all the files. I want to minimize possibility of writing duplicate records.

答: I suggest you use replicasets for this. Set the number of replica to 1. More here https://kubernetes.io/docs/concepts/workloads/controllers/replicaset/#when-to-use-a-replicaset</p>

Title: Kubernetes Job: exactly one pod


问:
How to reach 100% code coverage with expectexception in PHPUnit
I'm testing that, given an input that must fail, handleMatchResults will throw a RouteNotFoundException. This is the actual test's code:

```<code>public function test_not_found_match_throws_NotFoundException()
{
    $this->expectException(RouteNotFoundException::class);
    $request = $this->prophet->prophesize(ServerRequest::class);
    $this->router->handleMatchResults([0, []], $request->reveal());
}
</code>```

Everything goes as expected, my test pass, but, when I run phpunit --coverage-text (or any other coverage type) I have that, the last line of this test, and the last line of another similar test, are unreachable/not-executed. I can understand that those are not executed because, if the code is correct, the last line of this test won't be ever executed because

$this->router->handleMatchResults([0, []], $request->reveal());

Will always throw an exception and the execution of the function will end. So, how do I reach 100% coverage of my class?

答:
No, you wont get 100%, because metric should not be on your TEST.
You should use whitelist or blacklist in configuration, to ommit this tests.

It is mandatory to configure a whitelist for telling PHPUnit which
  sourcecode files to include in the code coverage report.

```<code><filter>
  <whitelist processUncoveredFilesFromWhitelist="true">
    <directory suffix=".php">/path/to/files</directory>
    <file>/path/to/file</file>
    <exclude>
      <directory suffix=".php">/path/to/files</directory>
      <file>/path/to/file</file>
    </exclude>
  </whitelist>
</filter>
</code>```

Your code will mark, that went to handleMatchResults and execute throw. In other test, you will execute positive scenario with this function.

That way you should have 100% coverage.

Body:
I'm testing that, given an input that must fail, handleMatchResults will throw a RouteNotFoundException. This is the actual test's code:

public function test_not_found_match_throws_NotFoundException()
{
    $this->expectException(RouteNotFoundException::class);
    $request = $this->prophet->prophesize(ServerRequest::class);
    $this->router->handleMatchResults([0, []], $request->reveal());
}

Everything goes as expected, my test pass, but, when I run phpunit --coverage-text (or any other coverage type) I have that, the last line of this test, and the last line of another similar test, are unreachable/not-executed. I can understand that those are not executed because, if the code is correct, the last line of this test won't be ever executed because

$this->router->handleMatchResults([0, []], $request->reveal());

Will always throw an exception and the execution of the function will end. So, how do I reach 100% coverage of my class?

Body:
No, you wont get 100%, because metric should not be on your TEST.
You should use whitelist or blacklist in configuration, to ommit this tests.

It is mandatory to configure a whitelist for telling PHPUnit which
  sourcecode files to include in the code coverage report.

<filter>
  <whitelist processUncoveredFilesFromWhitelist="true">
    <directory suffix=".php">/path/to/files</directory>
    <file>/path/to/file</file>
    <exclude>
      <directory suffix=".php">/path/to/files</directory>
      <file>/path/to/file</file>
    </exclude>
  </whitelist>
</filter>

Your code will mark, that went to handleMatchResults and execute throw. In other test, you will execute positive scenario with this function.

That way you should have 100% coverage.


问:
tcsh alias with if-then-else condition
I am trying to have an alias with if-then-else condition
on a command result.

the alias will get a file pattern

if there is just one file it will open the file

if there is more or less then 1 files - it will indicate with a message.

the alias I have tried is:

```<code>alias atest 'if \("ls \!:1" > 0 \)  "nedit ls \!:1" else "echo cant open the file" '
</code>```

答:
You can't do this with an alias. An alias can only expand into a one-line command, but if requires multiple lines.

Instead, use a shell script. The script doesn't have to be in the same language you use interactively, so you can use POSIX shell, which is generally considered much better for programming than C shell (see Csh Programming Considered Harmful).

```<code>#!/bin/sh
if [ $# -eq 1 ]
then nedit "$1"
else
    echo "Can't open the file"
    exit 1
fi
</code>```

Put this in a file named atest, give it execute permissions, and put it in a directory that's in your $PATH.

Title: tcsh alias with if-then-else condition

Body:
I am trying to have an alias with if-then-else condition
on a command result.

the alias will get a file pattern

if there is just one file it will open the file

if there is more or less then 1 files - it will indicate with a message.

the alias I have tried is:

alias atest 'if \("ls \!:1" > 0 \)  "nedit ls \!:1" else "echo cant open the file" '

Body:
You can't do this with an alias. An alias can only expand into a one-line command, but if requires multiple lines.

Instead, use a shell script. The script doesn't have to be in the same language you use interactively, so you can use POSIX shell, which is generally considered much better for programming than C shell (see Csh Programming Considered Harmful).

#!/bin/sh
if [ $# -eq 1 ]
then nedit "$1"
else
    echo "Can't open the file"
    exit 1
fi

Put this in a file named atest, give it execute permissions, and put it in a directory that's in your $PATH.


问:
How to add default values to input fields in Thymeleaf
I am programming in Spring and using Thymeleaf as my view, and am trying to create a form where users can update their profile. I have a profile page which lists the user's information (first name, last name, address, etc), and there is a link which says "edit profile". When that link is clicked it takes them to a form where they can edit their profile. The form consists of text fields that they can input, just like your standard registration form.

Everything works fine, but my question is, when that link is clicked, how do I add the user's information to the input fields so that it is already present, and that they only modify what they want to change instead of having to re-enter all the fields.

This should behave just like a standard "edit profile" page.

Here is a segment of my edit_profile.html page:

First Name:

Here is the view controller method that returns edit_profile.html page:

```<code>@RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String getEditProfilePage(Model model) {
        model.addAttribute("currentUser", currentUser);
        System.out.println("current user firstname: " + currentUser.getFirstname());
        model.addAttribute("user", new User());
        return "edit_profile";
    }
</code>```

currentUser.getFirstname() prints out the expected value, but I'm getting blank input values in the form.

Thanks.

答:
I did not have a form with input elements but only a button that should call a specific Spring Controller method and submit an ID of an animal in a list (so I had a list of anmials already showing on my page). I struggled some time to figure out how to submit this id in the form. Here is my solution:

So I started having a form with just one input field (that I would change to a hidden field in the end). In this case of course the id would be empty after submitting the form.

```<code><form action="#" th:action="@{/greeting}" th:object="${animal}" method="post">
    <p>Id: <input type="text" th:field="*{id}" /></p>
    <p><input type="submit" value="Submit" /> </p>
</form>
</code>```

The following did not throw an error but neither did it submit the animalIAlreadyShownOnPage's ID.

```<code><form action="#" th:action="@{/greeting}" th:object="${animal}" method="post">
    <p>Id: <input type="text" th:value="${animalIAlreadyShownOnPage.id}" /></p>
    <p><input type="submit" value="Submit" /> </p>
</form>
</code>```

In another post user's recommended the "th:attr" attribute, but it didn't work either.

This finally worked - I simply added the name element ("id" is a String attribute in the Animal POJO).

```<code><form action="#" th:action="@{/greeting}" th:object="${animal}" method="post">
    <p>Id: <input type="text" th:value="${animalIAlreadyShownOnPage.id}" name="id" /></p>
    <p><input type="submit" value="Submit" /> </p>
</form>
</code>```

Body:
I am programming in Spring and using Thymeleaf as my view, and am trying to create a form where users can update their profile. I have a profile page which lists the user's information (first name, last name, address, etc), and there is a link which says "edit profile". When that link is clicked it takes them to a form where they can edit their profile. The form consists of text fields that they can input, just like your standard registration form.

Everything works fine, but my question is, when that link is clicked, how do I add the user's information to the input fields so that it is already present, and that they only modify what they want to change instead of having to re-enter all the fields.

This should behave just like a standard "edit profile" page.

Here is a segment of my edit_profile.html page:

First Name:

Here is the view controller method that returns edit_profile.html page:

@RequestMapping(value = "/edit", method = RequestMethod.GET)
    public String getEditProfilePage(Model model) {
        model.addAttribute("currentUser", currentUser);
        System.out.println("current user firstname: " + currentUser.getFirstname());
        model.addAttribute("user", new User());
        return "edit_profile";
    }

currentUser.getFirstname() prints out the expected value, but I'm getting blank input values in the form.

Thanks.

Body:
I did not have a form with input elements but only a button that should call a specific Spring Controller method and submit an ID of an animal in a list (so I had a list of anmials already showing on my page). I struggled some time to figure out how to submit this id in the form. Here is my solution:

So I started having a form with just one input field (that I would change to a hidden field in the end). In this case of course the id would be empty after submitting the form.

<form action="#" th:action="@{/greeting}" th:object="${animal}" method="post">
    <p>Id: <input type="text" th:field="*{id}" /></p>
    <p><input type="submit" value="Submit" /> </p>
</form>

The following did not throw an error but neither did it submit the animalIAlreadyShownOnPage's ID.

<form action="#" th:action="@{/greeting}" th:object="${animal}" method="post">
    <p>Id: <input type="text" th:value="${animalIAlreadyShownOnPage.id}" /></p>
    <p><input type="submit" value="Submit" /> </p>
</form>

In another post user's recommended the "th:attr" attribute, but it didn't work either.

This finally worked - I simply added the name element ("id" is a String attribute in the Animal POJO).

<form action="#" th:action="@{/greeting}" th:object="${animal}" method="post">
    <p>Id: <input type="text" th:value="${animalIAlreadyShownOnPage.id}" name="id" /></p>
    <p><input type="submit" value="Submit" /> </p>
</form>


问:
SQL query question: SELECT ... NOT IN
I am sure making a silly mistake but I can't figure what:

In SQL Server 2005 I am trying select all customers except those who have made a reservation before 2 AM.

When I run this query:

```<code>SELECT idCustomer FROM reservations
WHERE idCustomer NOT IN
  (SELECT distinct idCustomer FROM reservations
   WHERE DATEPART ( hour, insertDate) < 2)
</code>```

I get 0 results.

But

```<code>SELECT idCustomer FROM reservations
</code>```

returns 152.000 results and the "NOT IN" part:

```<code>SELECT distinct idCustomer FROM reservations
WHERE DATEPART ( hour, insertDate) < 2
</code>```

returns only 284 rows

答:
```<code>select * from table_name where id=5 and column_name not in ('sandy,'pandy');
</code>```

OwnerDisplayName: Dawkins

Title: SQL query question: SELECT ... NOT IN

Body:
I am sure making a silly mistake but I can't figure what:

In SQL Server 2005 I am trying select all customers except those who have made a reservation before 2 AM.

When I run this query:

SELECT idCustomer FROM reservations
WHERE idCustomer NOT IN
  (SELECT distinct idCustomer FROM reservations
   WHERE DATEPART ( hour, insertDate) < 2)

I get 0 results.

But

SELECT idCustomer FROM reservations

returns 152.000 results and the "NOT IN" part:

SELECT distinct idCustomer FROM reservations
WHERE DATEPART ( hour, insertDate) < 2

returns only 284 rows

LastEditorDisplayName: sblundy


问:
Is there any way to detect when a CSS file has been fully loaded?
I've been testing a lot of lazy-loaders for JavaScript and CSS that insert

答:
About the "load-checking CSS rules" :

If, in your JS script, you append in your head a style tag containing a simple rule like : #loadingCss { display: block; }

Than, you just have to add in all your CSS files something like : #loadingCss { display: none; }

In the head of your doc you append the style tag before the link tag. This way, the CSS rule in the CSS file will be more important (same selector -> same priority, the last one in the doc is the winner).

Than, in your JS script you just have to check #loadingCss visibility.
Once you know your CSS file is loaded, you can remove the style tag.

For the next CSS file you want to load, you can add this style tag again at the end of the head element.

This way, with only one rule, you can manage all your CSS files loading.
The only problem with this solution : You can't load more than one CSS file at a time. But I'm sure it's possible to find a way to do so.

But anyway, I'm not sure this solution (using a CSS rule to check loading) is a very good solution. Maybe there's other ways to do this.


问:
gst regular expression mismatch of group generates exception
I have a simple example in GNU Smalltalk 3.2.5 of attempting to group match on a key value setting:

```<code>st> m := 'a=b' =~ '(.*?)=(.*)'
MatchingRegexResults:'a=b'('a','b')
</code>```

The above example works just as expected. However, if there is no match to the second group (.*), an exception is generated:

```<code>st> m := 'a=' =~ '(.*?)=(.*)'
Object: Interval new "<-0x4ce2bdf0>" error: Invalid index 1: index out of range
SystemExceptions.IndexOutOfRange(Exception)>>signal (ExcHandling.st:254)
SystemExceptions.IndexOutOfRange class>>signalOn:withIndex: (SysExcept.st:660)
Interval>>first (Interval.st:245)
Kernel.MatchingRegexResults>>at: (Regex.st:382)
Kernel.MatchingRegexResults>>printOn: (Regex.st:305)
Kernel.MatchingRegexResults(Object)>>printString (Object.st:534)
Kernel.MatchingRegexResults(Object)>>printNl (Object.st:571)
</code>```

I don't understand this behavior. I would have expected the result to be ('a', nil) and that m at: 2 to be nil. I tried a different approach as follows:

```<code>st> 'a=' =~ '(.*?)=(.*)' ifMatched: [ :m | 'foo' printNl ]
'foo'
'foo'
</code>```

Which determines properly that there's a match to the regex. But I still can't check if a specific group is nil:

```<code>st> 'a=' =~ '(.*?)=(.*)' ifMatched: [ :m | (m at: 2) ifNotNil: [ (m at: 2) printNl ] ]
Object: Interval new "<-0x4ce81b58>" error: Invalid index 1: index out of range
SystemExceptions.IndexOutOfRange(Exception)>>signal (ExcHandling.st:254)
SystemExceptions.IndexOutOfRange class>>signalOn:withIndex: (SysExcept.st:660)
Interval>>first (Interval.st:245)
Kernel.MatchingRegexResults>>at: (Regex.st:382)
optimized [] in UndefinedObject>>executeStatements (a String:1)
Kernel.MatchingRegexResults>>ifNotMatched:ifMatched: (Regex.st:322)
Kernel.MatchingRegexResults(RegexResults)>>ifMatched: (Regex.st:188)
UndefinedObject>>executeStatements (a String:1)
nil
st>
</code>```

I don't understand this behavior. I would have expected the result to be ('a', nil) and that m at: 2 to be nil. At least that's the way it works in any other language I've used regex in. This makes me think maybe I'm not doing something correct with my syntax.

My question this is: do I have the correct syntax for attempting to match ASCII key value pairs like this (for example, in parsing environment settings)? And if I do, why is an exception being generated, or is there a way I can have it provide a result that I can check without generating an exception?

I found a related issue reported at gnu.org from Dec 2013 with no responses.

答:
```<code>ValidationExpression="[0-9]{2}[(a-z)(A-Z)]{5}\d{4}[(a-z)(A-Z)]{1}\d{1}Z\d{1}"
SetFocusOnError="true" ControlToValidate="txtGST" Display="Dynamic" runat="server" ErrorMessage="Invalid GST No." ValidationGroup="Add"  ForeColor="Red"></asp:RegularExpressionValidator>
</code>```

Body:
I have a simple example in GNU Smalltalk 3.2.5 of attempting to group match on a key value setting:

st> m := 'a=b' =~ '(.*?)=(.*)'
MatchingRegexResults:'a=b'('a','b')

The above example works just as expected. However, if there is no match to the second group (.*), an exception is generated:

st> m := 'a=' =~ '(.*?)=(.*)'
Object: Interval new "<-0x4ce2bdf0>" error: Invalid index 1: index out of range
SystemExceptions.IndexOutOfRange(Exception)>>signal (ExcHandling.st:254)
SystemExceptions.IndexOutOfRange class>>signalOn:withIndex: (SysExcept.st:660)
Interval>>first (Interval.st:245)
Kernel.MatchingRegexResults>>at: (Regex.st:382)
Kernel.MatchingRegexResults>>printOn: (Regex.st:305)
Kernel.MatchingRegexResults(Object)>>printString (Object.st:534)
Kernel.MatchingRegexResults(Object)>>printNl (Object.st:571)

I don't understand this behavior. I would have expected the result to be ('a', nil) and that m at: 2 to be nil. I tried a different approach as follows:

st> 'a=' =~ '(.*?)=(.*)' ifMatched: [ :m | 'foo' printNl ]
'foo'
'foo'

Which determines properly that there's a match to the regex. But I still can't check if a specific group is nil:

st> 'a=' =~ '(.*?)=(.*)' ifMatched: [ :m | (m at: 2) ifNotNil: [ (m at: 2) printNl ] ]
Object: Interval new "<-0x4ce81b58>" error: Invalid index 1: index out of range
SystemExceptions.IndexOutOfRange(Exception)>>signal (ExcHandling.st:254)
SystemExceptions.IndexOutOfRange class>>signalOn:withIndex: (SysExcept.st:660)
Interval>>first (Interval.st:245)
Kernel.MatchingRegexResults>>at: (Regex.st:382)
optimized [] in UndefinedObject>>executeStatements (a String:1)
Kernel.MatchingRegexResults>>ifNotMatched:ifMatched: (Regex.st:322)
Kernel.MatchingRegexResults(RegexResults)>>ifMatched: (Regex.st:188)
UndefinedObject>>executeStatements (a String:1)
nil
st>

I don't understand this behavior. I would have expected the result to be ('a', nil) and that m at: 2 to be nil. At least that's the way it works in any other language I've used regex in. This makes me think maybe I'm not doing something correct with my syntax.

My question this is: do I have the correct syntax for attempting to match ASCII key value pairs like this (for example, in parsing environment settings)? And if I do, why is an exception being generated, or is there a way I can have it provide a result that I can check without generating an exception?

I found a related issue reported at gnu.org from Dec 2013 with no responses.