问:
How do I focus a foreign window?
I have an application which may only have one instance of itself open at a time. To enforce this, I use this code:

```<code>System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcesses();
System.Diagnostics.Process me = System.Diagnostics.Process.GetCurrentProcess();
foreach (System.Diagnostics.Process p in myProcesses)
{
    if (p.ProcessName == me.ProcessName)
        if (p.Id != me.Id)
        {
            //if already running, abort this copy.
            return;
        }
}
//launch the application.
//...
</code>```

It works fine. I would also like it to be able to focus the form of the already-running copy.  That is, before returning, I want to bring the other instance of this application into the foreground.

How do I do that?

SetForegroundWindow works, to a point:

```<code>[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

// ...
if (p.Id != me.Id)
{
    //if already running, focus it, and then abort this copy.
    SetForegroundWindow(p.MainWindowHandle);
    return;
}
// ...
</code>```

This does bring the window to the foreground if it is not minimized.  Awesome.
If the window IS minimized, however, it remains minimized.

It needs to un-minimize.

Solution via SwitchToThisWindow (Works!):

```<code>[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);

[STAThread]
static void Main()
{
    System.Diagnostics.Process me = System.Diagnostics.Process.GetCurrentProcess();
    System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcessesByName(me.ProcessName);
    foreach (System.Diagnostics.Process p in myProcesses)
    {
        if (p.Id != me.Id)
        {
            SwitchToThisWindow(p.MainWindowHandle, true);
            return;
        }
    }
    //now go ahead and start our application ;-)
}
</code>```

答:
I believe you will want to use SetForegroundWindow

MSDN Example

OwnerDisplayName: Blinky

Title: How do I focus a foreign window?

Body:
I have an application which may only have one instance of itself open at a time. To enforce this, I use this code:

System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcesses();
System.Diagnostics.Process me = System.Diagnostics.Process.GetCurrentProcess();
foreach (System.Diagnostics.Process p in myProcesses)
{
    if (p.ProcessName == me.ProcessName)
        if (p.Id != me.Id)
        {
            //if already running, abort this copy.
            return;
        }
}
//launch the application.
//...

It works fine. I would also like it to be able to focus the form of the already-running copy.  That is, before returning, I want to bring the other instance of this application into the foreground.

How do I do that?

SetForegroundWindow works, to a point:

[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

// ...
if (p.Id != me.Id)
{
    //if already running, focus it, and then abort this copy.
    SetForegroundWindow(p.MainWindowHandle);
    return;
}
// ...

This does bring the window to the foreground if it is not minimized.  Awesome.
If the window IS minimized, however, it remains minimized.

It needs to un-minimize.

Solution via SwitchToThisWindow (Works!):

[System.Runtime.InteropServices.DllImport("user32.dll")]
public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);

[STAThread]
static void Main()
{
    System.Diagnostics.Process me = System.Diagnostics.Process.GetCurrentProcess();
    System.Diagnostics.Process[] myProcesses = System.Diagnostics.Process.GetProcessesByName(me.ProcessName);
    foreach (System.Diagnostics.Process p in myProcesses)
    {
        if (p.Id != me.Id)
        {
            SwitchToThisWindow(p.MainWindowHandle, true);
            return;
        }
    }
    //now go ahead and start our application ;-)
}

LastEditorDisplayName: Blinky

OwnerDisplayName: cmsjr


来源: stackexchange

问:
IE8 breaking on hover of select box's options
Okay, so I have the following code that works fine in all browsers except IE..

```<code>$('input[title!=], select[title!=]').mouseenter(function(){
    if ($(this).data('focused')!='y') {
        $(this).data('t', this.title).data('focused', 'y');
        this.title = '';
        var pos = $(this).position();
        $('body').append('<div id="toolTip" class="round-5 shadow-heavy"><img class="arrow" src="/images/bg/toolTip.png" alt="" />'+($(this).data('t'))+'</div>');
        $('#toolTip').css('top',(pos.top+($(this).height()/2)-($('#toolTip').innerHeight()/2))+'px').css('left',(pos.left+($(this).innerWidth())+20)+'px');
    }
}).mouseleave(function(){
    if ($(this).data('focused')!='n') {
        $(this).data('focused', 'n');
        this.title = $(this).data('t');
        $('#toolTip').remove();
    }
}).focus(function(){if($(this).data('focused')!='y'){$(this).trigger('mouseenter');}}).blur(function(){if($(this).data('focused')!='n'){$(this).trigger('mouseleave');}});
</code>```

Now, in IE if you open the select box and move your mouse over one of the options the box closes. What's causing it is the IE apparently doesn't count the dropdown box of options as part of the select element so it triggers the mouseleave event.

Does anyone know a fix around this?

答:
IE in particular has a very bizarre implementation of <select>, since IE6 (possibly earlier) it was pulled in from winforms...which is also the reason it sits on top of anything but an  in older versions.

Unfortunately, events on or involving <option> elements are unreliable at best (like you're seeing)...and can't be trusted in IE.  You could disable the behavior in IE, but that's about the only "fix" there is.

The all-out alternative is to replace the <select> completely, there are a few jQuery plugins out there that do this, check out this question for options around that.

ContentLicense: CC BY-SA 2.5

Body:
Okay, so I have the following code that works fine in all browsers except IE..

$('input[title!=], select[title!=]').mouseenter(function(){
    if ($(this).data('focused')!='y') {
        $(this).data('t', this.title).data('focused', 'y');
        this.title = '';
        var pos = $(this).position();
        $('body').append('
'+($(this).data('t'))+'
');
        $('#toolTip').css('top',(pos.top+($(this).height()/2)-($('#toolTip').innerHeight()/2))+'px').css('left',(pos.left+($(this).innerWidth())+20)+'px');
    }
}).mouseleave(function(){
    if ($(this).data('focused')!='n') {
        $(this).data('focused', 'n');
        this.title = $(this).data('t');
        $('#toolTip').remove();
    }
}).focus(function(){if($(this).data('focused')!='y'){$(this).trigger('mouseenter');}}).blur(function(){if($(this).data('focused')!='n'){$(this).trigger('mouseleave');}});

Now, in IE if you open the select box and move your mouse over one of the options the box closes. What's causing it is the IE apparently doesn't count the dropdown box of options as part of the select element so it triggers the mouseleave event.

Does anyone know a fix around this?

Body:
IE in particular has a very bizarre implementation of <select>, since IE6 (possibly earlier) it was pulled in from winforms...which is also the reason it sits on top of anything but an <iframe> in older versions.

Unfortunately, events on or involving <option> elements are unreliable at best (like you're seeing)...and can't be trusted in IE.  You could disable the behavior in IE, but that's about the only "fix" there is.

The all-out alternative is to replace the <select> completely, there are a few jQuery plugins out there that do this, check out this question for options around that.


问:
C If statement Error: exited with non-zero status
I'm new to c, and I am trying to make a typing game.But the if statement doesn't work,and the output is "exited with non-zero status".May be the problem is cause by the IDE,I can't figure it out,thanks.</p>

```<code>#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main (void)
{
  char start;
  printf ("here is a typing game\n");
  printf ("type any key to start\n");
  scanf ("%c", &start);
  void game()
  {
    int i;
    char answer;
    char type[20];
    {
      for (i = 0; i < 20; i++)
      {
        printf ("%c", 'a' + (random() % 26));
      }
    }
    scanf ("%s", answer);
    if (strcmp(answer,type) == 0)
    {
      printf ("good\n");
    }
    else
    {
      printf ("so bad\n");
    }
  }
  game();
}
</code>```

答:
```<code>#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void game();

int main (void)
{
  char start;

  srand(time(NULL));//seed rand function with time to generate "near to pseudo random numbers"(note: This is not "really" pseudo anyways!)
  printf ("here is a typing game\n");
  printf ("type any key to start\n");
  scanf("%c",&start);
//define your function outside main
  game();//call your function here
}
void game()
  {
    int i;
    char answer[20];//answer should also be an array
    char type[20]="";//initialize type this way to avoid unnecessary characters initialization

    {
      for (i = 0; i < 19; i++)//should be 19 not 20... Last character has to be null
      {
        printf ("%c", type[i]='a' + (rand() % 26));//You forgot to add the random characters in type array and
                                                   //rand should be called this way

      }
    }
    scanf ("%s", answer);
    if (strcmp(answer,type) == 0)
    {
      printf ("good\n");
    }
    else
    {
      printf ("so bad\n");
    }
  }
</code>```

Suggestion: Improvisations should still be made, like taking input using fgets() and not scanf and managing answer array overflow at input.

ContentLicense: CC BY-SA 3.0

Body:
I'm new to c, and I am trying to make a typing game.But the if statement doesn't work,and the output is "exited with non-zero status".May be the problem is cause by the IDE,I can't figure it out,thanks.

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main (void)
{
  char start;
  printf ("here is a typing game\n");
  printf ("type any key to start\n");
  scanf ("%c", &start);
  void game()
  {
    int i;
    char answer;
    char type[20];
    {
      for (i = 0; i < 20; i++)
      {
        printf ("%c", 'a' + (random() % 26));
      }
    }
    scanf ("%s", answer);
    if (strcmp(answer,type) == 0)
    {
      printf ("good\n");
    }
    else
    {
      printf ("so bad\n");
    }
  }
  game();
}

Body:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void game();

int main (void)
{
  char start;

  srand(time(NULL));//seed rand function with time to generate "near to pseudo random numbers"(note: This is not "really" pseudo anyways!)
  printf ("here is a typing game\n");
  printf ("type any key to start\n");
  scanf("%c",&start);
//define your function outside main
  game();//call your function here
}
void game()
  {
    int i;
    char answer[20];//answer should also be an array
    char type[20]="";//initialize type this way to avoid unnecessary characters initialization

    {
      for (i = 0; i < 19; i++)//should be 19 not 20... Last character has to be null
      {
        printf ("%c", type[i]='a' + (rand() % 26));//You forgot to add the random characters in type array and
                                                   //rand should be called this way

      }
    }
    scanf ("%s", answer);
    if (strcmp(answer,type) == 0)
    {
      printf ("good\n");
    }
    else
    {
      printf ("so bad\n");
    }
  }

Suggestion: Improvisations should still be made, like taking input using fgets() and not scanf and managing answer array overflow at input.


问:
I'm getting ORA-00936: missing expression. Why is that? Can someone help me out?
```<code>INSERT ALL
INTO EMPLOYEE
(EMPL_CODE_ID, EMPL_FIRST_NAME, EMPL_LAST_NAME, EMPL_ADDRESS,
EMPL_WORKING_AREA, EMPL_TITLE, EMPL_PHONE_NUMBER, EMPL_DOB,
EMPL_STATE, EMPL_COUNTRY)
VALUES
('A4','ROB','BOB','123 TREE TOP','FRONT DESK','RECEPTIONIST','301-000-0004','01/04/1994','MD','USA')

INTO EMPLOYEE
(EMPL_CODE_ID, EMPL_FIRST_NAME, EMPL_LAST_NAME, EMPL_ADDRESS,
EMPL_WORKING_AREA, EMPL_TITLE, EMPL_PHONE_NUMBER, EMPL_DOB,
EMPL_STATE, EMPL_COUNTRY)
VALUES
('A5','JOSH','FROG','125 TREE BARK LANE','FRONT DESK','RECEPTIONIST','301-000-0005','08/09/1994','VA','USA')
INTO EMPLOYEE
(EMPL_CODE_ID, EMPL_FIRST_NAME, EMPL_LAST_NAME, EMPL_ADDRESS,
EMPL_WORKING_AREA, EMPL_TITLE, EMPL_PHONE_NUMBER, EMPL_DOB,
EMPL_STATE, EMPL_COUNTRY)
VALUES
INTO EMPLOYEE
(EMPL_CODE_ID, EMPL_FIRST_NAME, EMPL_LAST_NAME, EMPL_ADDRESS,
EMPL_WORKING_AREA, EMPL_TITLE, EMPL_PHONE_NUMBER, EMPL_DOB,
EMPL_STATE, EMPL_COUNTRY)
VALUES
INTO EMPLOYEE
(EMPL_CODE_ID, EMPL_FIRST_NAME, EMPL_LAST_NAME, EMPL_ADDRESS,
EMPL_WORKING_AREA, EMPL_TITLE, EMPL_PHONE_NUMBER, EMPL_DOB,
EMPL_STATE, EMPL_COUNTRY)
VALUES
('A6','FRED','KIM','123 SENECA WAY','FRONT DESK','RECEPTIONIST','301-000-0006','03/23/1997','VA','USA')
SELECT * FROM DUAL;
</code>```

答:
The easiest way of inserting records into a single table is the straightforward INSERT INTO ... SELECT FROM. Use UNION ALL to make a set of records:

```<code>INSERT INTO EMPLOYEE
(EMPL_CODE_ID, EMPL_FIRST_NAME, EMPL_LAST_NAME, EMPL_ADDRESS, EMPL_WORKING_AREA, EMPL_TITLE, EMPL_PHONE_NUMBER, EMPL_DOB, EMPL_STATE, EMPL_COUNTRY)
select 'A4','ROB','BOB','123 TREE TOP','FRONT DESK','RECEPTIONIST','301-000-0004','01/04/1994','MD','USA'
from dual union all
select 'A5','JOSH','FROG','125 TREE BARK LANE','FRONT DESK','RECEPTIONIST','301-000-0005','08/09/1994','VA','USA'
from dual union all
select 'A6','FRED','KIM','123 SENECA WAY','FRONT DESK','RECEPTIONIST','301-000-0006','03/23/1997','VA','USA'
from dual
/
</code>```

Body:
The easiest way of inserting records into a single table is the straightforward INSERT INTO ... SELECT FROM. Use UNION ALL to make a set of records:

INSERT INTO EMPLOYEE
(EMPL_CODE_ID, EMPL_FIRST_NAME, EMPL_LAST_NAME, EMPL_ADDRESS, EMPL_WORKING_AREA, EMPL_TITLE, EMPL_PHONE_NUMBER, EMPL_DOB, EMPL_STATE, EMPL_COUNTRY)
select 'A4','ROB','BOB','123 TREE TOP','FRONT DESK','RECEPTIONIST','301-000-0004','01/04/1994','MD','USA'
from dual union all
select 'A5','JOSH','FROG','125 TREE BARK LANE','FRONT DESK','RECEPTIONIST','301-000-0005','08/09/1994','VA','USA'
from dual union all
select 'A6','FRED','KIM','123 SENECA WAY','FRONT DESK','RECEPTIONIST','301-000-0006','03/23/1997','VA','USA'
from dual
/


问:
Strings or integers for Steam IDs
What is the preferred datatype for storing Steam IDs? These IDs are very similar to credit card numbers, but is different cases of use. Until now I'm using unsigned big integer but I'm not 100% sure yet. If the ID starts with a zero number, can cause issues? Eg ID: 76561197960287930</p>

答:
In general number take less space on the disk to store and on the transfer from the database to the application compared to strings. They are for the same reason  faster to compare e.g. in the where-clause of a query.

Have a look here for the bytes needed to store numbers and bytes to store strings.

In the database the numbers are stored without leading zeros. You could fill up your numbers with leading zeros in your application after loading them from the database, if the numbers always have a fixed size.

But if the numbers can have leading zeros strings are easier to handle, because you do not have to implement additional logic for edgecases like leading zeros.

Title: Strings or integers for Steam IDs


问:
Adwords Scripts - access keywords search terms
I'm trying to access the keywords search terms report, and apply query on it by "Add/Exclude" column, cost, etc.

Couldn't find it in the docs, there is any way to get the report?

Thanks

Edit:
There is an existing option to save to search report and scheduled it, so if there is a chance to access the reports sections it would be great either.

答:
Take a look at this solution.

You're able to acquire the data from the search query report through an AWQL query. Example as used in the linked solution:

```<code>var report = AdWordsApp.report(
   "SELECT Query,Clicks,Cost,Ctr,ConversionRate,CostPerConversion,Conversions,CampaignId,AdGroupId " +
   " FROM SEARCH_QUERY_PERFORMANCE_REPORT " +
   " WHERE " +
       " Conversions > 0" +
       " AND Impressions > " + IMPRESSIONS_THRESHOLD +
       " AND AverageCpc > " + AVERAGE_CPC_THRESHOLD +
   " DURING LAST_7_DAYS");
</code>```

Body:
Take a look at this solution.

You're able to acquire the data from the search query report through an AWQL query. Example as used in the linked solution:

var report = AdWordsApp.report(
   "SELECT Query,Clicks,Cost,Ctr,ConversionRate,CostPerConversion,Conversions,CampaignId,AdGroupId " +
   " FROM SEARCH_QUERY_PERFORMANCE_REPORT " +
   " WHERE " +
       " Conversions > 0" +
       " AND Impressions > " + IMPRESSIONS_THRESHOLD +
       " AND AverageCpc > " + AVERAGE_CPC_THRESHOLD +
   " DURING LAST_7_DAYS");


问:
Devise login succeed when not confirmed
Could you tell me how to integrate the confirmed? attribute into the session-login process?

I've set up a working app with devise with confirmable and authenticatable enabled...
But I can log in with a user-model that isn't confirmed!

UPDATE

I've commented on the confirmable-section in my migration.

```<code>  # schema.rb
  create_table "users", :force => true do |t|
    t.string   "email",                                        :default => "", :null => false
    t.string   "encrypted_password",            :limit => 128, :default => "", :null => false
    t.string   "password_salt",                                :default => "", :null => false
    t.string   "confirmation_token"
    t.datetime "confirmed_at"
    t.datetime "confirmation_sent_at"
    ....
  end

# user.rb
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :confirmable, :lockable, :timeoutable, :token_authenticatable
  ...
end

# routes.rb
devise_for :users, :controllers => { :passwords => "password_resets" } do
  # this doesn't matter to my mentioned problem
  get "instruction", :to => "password_resets#instruction", :path => "/users/password/instruction", :as => "instruction_user_password"
end
</code>```

答:
argh...

I set the wrong configuration in devise.rb

```<code>  # ==> Configuration for :confirmable
  # The time you want to give your user to confirm his account. During this time
  # he will be able to access your application without confirming. The default is nil.
  # When confirm_within is zero, the user won't be able to sign in without confirming.
  # You can use this to let your user access some features of your application
  # without confirming the account, but blocking it after a certain period
  # (ie 2 days).
  config.confirm_within = 2.days

  # I didn't read that the user has access at this time
</code>```

ContentLicense: CC BY-SA 4.0

Title: Devise login succeed when not confirmed

Body:
Could you tell me how to integrate the confirmed? attribute into the session-login process?

I've set up a working app with devise with confirmable and authenticatable enabled...
But I can log in with a user-model that isn't confirmed!

UPDATE

I've commented on the confirmable-section in my migration.

  # schema.rb
  create_table "users", :force => true do |t|
    t.string   "email",                                        :default => "", :null => false
    t.string   "encrypted_password",            :limit => 128, :default => "", :null => false
    t.string   "password_salt",                                :default => "", :null => false
    t.string   "confirmation_token"
    t.datetime "confirmed_at"
    t.datetime "confirmation_sent_at"
    ....
  end

# user.rb
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable,
         :confirmable, :lockable, :timeoutable, :token_authenticatable
  ...
end

# routes.rb
devise_for :users, :controllers => { :passwords => "password_resets" } do
  # this doesn't matter to my mentioned problem
  get "instruction", :to => "password_resets#instruction", :path => "/users/password/instruction", :as => "instruction_user_password"
end

Body:
argh...

I set the wrong configuration in devise.rb

  # ==> Configuration for :confirmable
  # The time you want to give your user to confirm his account. During this time
  # he will be able to access your application without confirming. The default is nil.
  # When confirm_within is zero, the user won't be able to sign in without confirming.
  # You can use this to let your user access some features of your application
  # without confirming the account, but blocking it after a certain period
  # (ie 2 days).
  config.confirm_within = 2.days

  # I didn't read that the user has access at this time


问:
Chart.js size not adapting to div
I have tried so many things (modify css, add inline css to canvas, add inline css to a wrapper div of canvas) but I still can't make the chart fit in the panel properly.

Here is the HTML

```<code>        <section class="panel">
            <header class="panel-heading">
                Temp
            </header>
                <canvas id="tempChart"></canvas>
        </section>
</code>```

Here is the js code

```<code><script>

var data = {
    labels: ["January", "Aary", "March", "April", "May", "June"],
    datasets: [{
        label: "My First dataset",
        fillColor: 'rgba(220,220,220,0)',
        strokeColor: "rgba(220,220,220,1)",
        pointColor: 'red',
        pointStrokeColor: "#fff",
        pointHighlightFill: "#fff",
        pointHighlightStroke: "rgba(220,220,220,1)",
        data: [65, 59, 80, 81, 56, 55, 40]
    } ]
};

var option = {
    responsive: true,

};

var ctx = $("#tempChart").get(0).getContext("2d");
var myLineChart = new Chart(ctx).Line(data, option);
</code>```

The class panel in CSS contains only graphic things such as border background color and so on.
By the way I am using Bootstrap grid.
Thanks for your help.

答:
have you tried to set all your charts responsive with default value : Chart.defaults.global.responsive = true;

Your global synthax seems correct has you setted up

```<code>var options = { responsive:true }
</code>```

However; it's a tiny detail but you added a coma after that true.
I suggest to remove it.

as @brian suggested; please; inform us the version of the lib.
Add a jsfindle is even better

Title: Chart.js size not adapting to div

Body:
I have tried so many things (modify css, add inline css to canvas, add inline css to a wrapper div of canvas) but I still can't make the chart fit in the panel properly.

Here is the HTML

                Temp

                <canvas id="tempChart"></canvas>

Here is the js code

Body:
have you tried to set all your charts responsive with default value : Chart.defaults.global.responsive = true;

Your global synthax seems correct has you setted up

var options = { responsive:true }

However; it's a tiny detail but you added a coma after that true.
I suggest to remove it.

as @brian suggested; please; inform us the version of the lib.
Add a jsfindle is even better


问:
What is the most efficient way of visiting neighbor elements in a 2-D array in Go?
The problem I met is I have to visit all the eight neighbors of an element [i, j] in a 2D array.

However, considering the error of array out of bound, I have to do a lot of if else statement on [i-1, j] or [i+1, j]...It's kind of verbose to me.

So I wonder if there is any efficient way to implement this kind of problem in Go?

Like error-catching system?

答:
The general solution would follow the pseudo-code presented here.

See for a Go example this yucchiy/minesweeper field.go#GetNeighbors(x, y int).

It depends if you can enrich your data structure with an actual Array object composed of Fields, each one knowing its neighbor. Then "visiting neighbor elements in a 2-D array" become asking a Field for the list of Fields which are its neighbor.


问:
How to remove non-numeric lines from multi-text files?
I have some text files with strange characters.

They look like this,

How could I remove the lines with strange codes?

Thank you.

答:
Looks like you want to allow the following characters: 0-9,.-/ and a space.

Do a grep that looks for things that are NOT that, and print everything else -v:

```<code>grep -v '[^0-9,./ ]' file.txt
</code>```

Body:
Looks like you want to allow the following characters: 0-9,.-/ and a space.

Do a grep that looks for things that are NOT that, and print everything else -v:

grep -v '[^0-9,./ ]' file.txt


问:
How can I hide a table until filtered/input entered in search
I'm new to web developing but catching on fairly quickly. I'm developing a wiki page for my company and I have a filter table built but I want to hide the table until the filter function is applied when a user enters their search text. So this way it only shows the text input box and then when they type in their search the table results will THEN show.

I'm using this Javascript for the filtering:

```<code>  function ContactsearchFX() {
  var input, filter, table, tr, td, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");
  for (i = 0; i < tr.length; i++) {
     td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";

      }
    }
  }
}
</code>```

on a basic search table with this html code:

```<code><input type="text" id="myInput"            onkeyup="ContactsearchFX()" placeholder="Search for           names..">

<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:40%;">Number</th>
  </tr>
   <tr>
    <td>contact</td>
    <td>number</td>
  </tr>
     <tr>
    <td>contact</td>
    <td>number</td>
  </tr>
  <tr>
    <td>contact</td>
    <td>number</td>
  </tr>
</code>```

....and so on.

答:
I would suggest running the ContactsearchFX function on page load:

```<code>document.addEventListener('DOMContentLoaded', ContactsearchFX);
</code>```

... and requiring that filter is not the empty string in the condition for displaying a row.

This has one particular advantage: some browsers remember the last text that was entered in the input box, and fill that text automatically again on page load. With this solution, the corresponding table rows will be filtered immediately.

For a more responsive effect, I would remove the onkeyup="ContactsearchFX()" HTML attribute, and instead add the following JavaScript:

```<code>document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('myInput').addEventListener('input', ContactsearchFX);
});
</code>```

Also consider using the rows and cells collections instead of getElementsByTagName

Probably you want to keep the header row out of the filtering process, and so your loop should start at 1 instead of 0.

document.addEventListener('DOMContentLoaded', function () {
    ContactsearchFX();
    document.getElementById('myInput').addEventListener('input', ContactsearchFX);
});

function ContactsearchFX() {
  var input, filter, table, tr, td, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.rows;
  for (i = 1; i
 -1
        ? "" : "none";
    }
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="myInput" placeholder="Search for           names..">

<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:40%;">Number</th>
  </tr>
  <tr>
    <td>test 1</td>
    <td>number</td>
  </tr>
  <tr>
    <td>test 2</td>
    <td>number</td>
  </tr>
  <tr>
    <td>test 3</td>
    <td>number</td>
  </tr>
</table></code>```

Body:
I'm new to web developing but catching on fairly quickly. I'm developing a wiki page for my company and I have a filter table built but I want to hide the table until the filter function is applied when a user enters their search text. So this way it only shows the text input box and then when they type in their search the table results will THEN show.

I'm using this Javascript for the filtering:

  function ContactsearchFX() {
  var input, filter, table, tr, td, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");
  for (i = 0; i
 -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";

      }
    }
  }
}

on a basic search table with this html code:

<input type="text" id="myInput"            onkeyup="ContactsearchFX()" placeholder="Search for           names..">

    Name
    Number

    contact
    number

    contact
    number

    contact
    number

....and so on.

Body:
I would suggest running the ContactsearchFX function on page load:

document.addEventListener('DOMContentLoaded', ContactsearchFX);

... and requiring that filter is not the empty string in the condition for displaying a row.

This has one particular advantage: some browsers remember the last text that was entered in the input box, and fill that text automatically again on page load. With this solution, the corresponding table rows will be filtered immediately.

For a more responsive effect, I would remove the onkeyup="ContactsearchFX()" HTML attribute, and instead add the following JavaScript:

document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('myInput').addEventListener('input', ContactsearchFX);
});

Also consider using the rows and cells collections instead of getElementsByTagName

Probably you want to keep the header row out of the filtering process, and so your loop should start at 1 instead of 0.

document.addEventListener('DOMContentLoaded', function () {
    ContactsearchFX();
    document.getElementById('myInput').addEventListener('input', ContactsearchFX);
});

function ContactsearchFX() {
  var input, filter, table, tr, td, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.rows;
  for (i = 1; i < tr.length; i++) {
    td = tr[i].cells[0];
    if (td) {
      tr[i].style.display = filter && td.textContent.toUpperCase().indexOf(filter) > -1
        ? "" : "none";
    }
  }
}

<input type="text" id="myInput" placeholder="Search for           names..">

<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:40%;">Number</th>
  </tr>
  <tr>
    <td>test 1</td>
    <td>number</td>
  </tr>
  <tr>
    <td>test 2</td>
    <td>number</td>
  </tr>
  <tr>
    <td>test 3</td>
    <td>number</td>
  </tr>
</table>


问:
How to return two different classes from single method
```<code>public ResponseEntity<Profile> getProfile(@PathVariable("id") String id){
    if(id != null){
    //getting CUSTOMER from DB
    returning EntityProfile

    if(CUSTOMER == null)
    //getting data from webservice
    returning Profile
</code>```

答:
You could try creating a new class which contains an EntityProfile property and a Profile property:

```<code>public class CombinedClass{
     EntityProfile entity;
     Profile profile;
}
</code>```

Then make your method return a CombinedClass with the class you need to return. Then on your receiving end, you just need to check if entity or profile are null before trying to get the data.

```<code>public ResponseEntity<CombinedClass> getProfile(@PathVariable("id") String id){
    CombinedClass combined = new CombinedClass();
    if(id != null){
        combined.EntityProfile = //the EntityProfile you'll return
    }
    if(CUSTOMER == null){
        combined.profile= //the Profile you'll return
    }
    return combined;
}
</code>```

A little more code could help to understand how you'd need it though.

Body:
You could try creating a new class which contains an EntityProfile property and a Profile property:

public class CombinedClass{
     EntityProfile entity;
     Profile profile;
}

Then make your method return a CombinedClass with the class you need to return. Then on your receiving end, you just need to check if entity or profile are null before trying to get the data.

public ResponseEntity<CombinedClass> getProfile(@PathVariable("id") String id){
    CombinedClass combined = new CombinedClass();
    if(id != null){
        combined.EntityProfile = //the EntityProfile you'll return
    }
    if(CUSTOMER == null){
        combined.profile= //the Profile you'll return
    }
    return combined;
}

A little more code could help to understand how you'd need it though.


问:
How do I set a blank value for an f.select form field
I am using the following to allow my users to select their sex in their profile.

```<code><%= f.select (:sex, %w{ Male Female }) %>
</code>```

How would I create a blank value that the list would default to if nothing has been passed to the user.sex column? I am simply passing male or female as a string.

The purpose is I want a blank value so a validation can make sure they are aware they have to select it.

答:
I think you can do something like this:</p>

```<code><%= f.select (:sex, %w{ Male Female }, {:include_blank => 'None Specified'} ) %>
</code>```

Body:
I am using the following to allow my users to select their sex in their profile.

<%= f.select (:sex, %w{ Male Female }) %>

How would I create a blank value that the list would default to if nothing has been passed to the user.sex column? I am simply passing male or female as a string.

The purpose is I want a blank value so a validation can make sure they are aware they have to select it.

Body:
I think you can do something like this:

<%= f.select (:sex, %w{ Male Female }, {:include_blank => 'None Specified'} ) %>


问:
Isolating span title from span using BeautifulsSoup
I have the following

```<code><h3>The price of something is <span title="60,487">60.5k</span></h3>
</code>```

I want to get the title from the span. How is that accomplished? This span title is dynamic and changes from the website.

答:
You can do this using CSS selectors.</p>

```<code>>>> from bs4 import BeautifulSoup as BS
>>> html = """<h3>The price of something is <span title="60,487">60.5k</span></h3>"""
>>> soup = BS(html, "html.parser")
>>> soup.select_one("h3 > span[title]").get("title")
'60,487'
</code>```

Body:
I have the following

The price of something is 60.5k

I want to get the title from the span. How is that accomplished? This span title is dynamic and changes from the website.

Body:
You can do this using CSS selectors.

>>> from bs4 import BeautifulSoup as BS
>>> html = """<h3>The price of something is <span title="60,487">60.5k</span></h3>"""
>>> soup = BS(html, "html.parser")
>>> soup.select_one("h3 > span[title]").get("title")
'60,487'


问:
cUrl on instagram to lookup accounts by email
Is it possible to search for an user (Not by their api https://api.instagram.com) but using php cUrl through the search box in their website at https://www.instagram.com/ (you have to login to see the search box at the top of the page)
I mean I know how to make a php script and make it log in and keep the session (learned from tutorials) but the problem is there are no action="" attribute in the form tag, nor there are any name="" attribute in their input tags.

I want to know what they are using as their backend?

I want to know how Instagram pass variables if their are no action and name attribute

How can I post using cUrl without the variable names.

答:
The form input doesn't necessarily need a name attribute and also doesn't need to be in a form element with an action tag. Javascript could be used to get the input data and sent to the server using ajax or maybe change the address to search for what has been inputed.
Basically javascript could be used to get the data. In this case you won't be able to use cURL if you don't know the url that receives the input on the server. </p>


问:
Download xlsx file passed from nodejs to frontend angularjs
I have a JSON array of objects that is a result of a function in nodejs.  I use json2xls to convert that to an excel file, and it downloads to the server (not in a public folder, and is formatted correctly in Excel).

I would like to send a response to the frontend with the json results (to display as a preview) and show a button they can click to download the xlsx file OR display the JSON results and automatically download the file.

But I can't get it, and I've tried so many things I'm going crazy.
My controller code (the part that creates the xls file):

```<code> var xls = json2xls(results,{});
 var today = (new Date()).toDateString('yyyy-mm-dd');
 var str = today.replace(/\s/g, '');
 var fileName = "RumbleExport_"+ str +".xlsx";
 var file = fs.writeFileSync(fileName,xls,'binary');
 res.download('/home/ubuntu/workspace/'+file);
</code>```

The frontend controller:

```<code>vm.exportData = function(day, event, division) {
        console.log('Export registrations button pressed.', vm.export);
      //send the search parameters to the backend to run checks
        $http.post('/api/exportData', vm.export).then(function(response){
            vm.results = response.data;
            console.log("Results",response);
            vm.exportMessage = "Found " + vm.results.length + " registrations.";
        })
        .catch(function(error){
          vm.exportError = error.data;
        });
    };
</code>```

The view:

```<code>//display a button to download the export file
<a target="_self" file="{{vm.results}}" download="{{vm.results}}">Download Export File</a>
</code>```

Someone please put me out of my misery.  All the classes I've taken and none have covered this.

答:
I FINALLY got it!  And since I searched forever trying to make something work, I'll share the answer:

On the backend:

```<code>//save the file to the public/exports folder
var file = fs.writeFileSync('./public/exports/'+fileName,xls,'binary');
//send the results to the frontend
res.json(200).json({results:results, fileName: fileName});
</code>```

On the frontend, use HTML to download a link to the file:

```<code><a href="exports/{{fileName}}" download>Save File</a>
</code>```

Body:
I have a JSON array of objects that is a result of a function in nodejs.  I use json2xls to convert that to an excel file, and it downloads to the server (not in a public folder, and is formatted correctly in Excel).

I would like to send a response to the frontend with the json results (to display as a preview) and show a button they can click to download the xlsx file OR display the JSON results and automatically download the file.

But I can't get it, and I've tried so many things I'm going crazy.
My controller code (the part that creates the xls file):

 var xls = json2xls(results,{});
 var today = (new Date()).toDateString('yyyy-mm-dd');
 var str = today.replace(/\s/g, '');
 var fileName = "RumbleExport_"+ str +".xlsx";
 var file = fs.writeFileSync(fileName,xls,'binary');
 res.download('/home/ubuntu/workspace/'+file);

The frontend controller:

vm.exportData = function(day, event, division) {
        console.log('Export registrations button pressed.', vm.export);
      //send the search parameters to the backend to run checks
        $http.post('/api/exportData', vm.export).then(function(response){
            vm.results = response.data;
            console.log("Results",response);
            vm.exportMessage = "Found " + vm.results.length + " registrations.";
        })
        .catch(function(error){
          vm.exportError = error.data;
        });
    };

The view:

//display a button to download the export file
Download Export File

Someone please put me out of my misery.  All the classes I've taken and none have covered this.

Body:
I FINALLY got it!  And since I searched forever trying to make something work, I'll share the answer:

On the backend:

//save the file to the public/exports folder
var file = fs.writeFileSync('./public/exports/'+fileName,xls,'binary');
//send the results to the frontend
res.json(200).json({results:results, fileName: fileName});

On the frontend, use HTML to download a link to the file:

<a href="exports/{{fileName}}" download>Save File</a>


问:
Laravel validating an integer, but getting a validation error must be an integer
I am trying to validate a phone number.  First I strip the '-' out then I convert the inputed string to an integer.  When I try to validate the integer I get an error that the input must be an integer.  However, I just converted the string to and integer.  Why am I getting this error and how do I fix it?

Here is my code

```<code>$request->val = str_replace('-', '', $request->val);
                Log::debug($request->val);
                Log::debug(gettype($request->val)); //outputs string
                $request->val = intval($request->val);
                Log::debug(gettype($request->val));//outputs integer
                $this->validate($request, [
                    'val' => 'Integer|min:10|max:15'//Get an error must be interget
                ]);
</code>```

答:
Use ->merge to alter the value of a request attribute, do not attempt to mutate it directly, as the state will not be saved:

```<code>$request->merge(['val', intval(str_replace('-', '', $request->val))]);
</code>```

Body:
I am trying to validate a phone number.  First I strip the '-' out then I convert the inputed string to an integer.  When I try to validate the integer I get an error that the input must be an integer.  However, I just converted the string to and integer.  Why am I getting this error and how do I fix it?

Here is my code

$request->val = str_replace('-', '', $request->val);
                Log::debug($request->val);
                Log::debug(gettype($request->val)); //outputs string
                $request->val = intval($request->val);
                Log::debug(gettype($request->val));//outputs integer
                $this->validate($request, [
                    'val' => 'Integer|min:10|max:15'//Get an error must be interget
                ]);

Body:
Use ->merge to alter the value of a request attribute, do not attempt to mutate it directly, as the state will not be saved:

$request->merge(['val', intval(str_replace('-', '', $request->val))]);


问:
Does this make a difference in using generics?
Are they exactly the same or used for different situations?

```<code>public List<? extends Object> do(){
   return ...
}
</code>```

VS

```<code>public List<Object> do(){
  return...
}
</code>```

答:
Those are not the same.

A List<? extends Object> may be a list of any type.

Since you don't know what type the list actually contains, you can't put anything into it.

Body:
Are they exactly the same or used for different situations?

public List<? extends Object> do(){
   return ...
}

VS

public List<Object> do(){
  return...
}


问:
Dataframe Sorting
I am working on Python pandas, beginning with sorting a dataframe I have created from a csv file. I am trying to create a for loop eventually, using values to compare. However, when I print the new values, they are using the original dataframe instead of the sorted version. How do I properly do the below?

Original CSV data:

```<code>date          fruit     quantity
4/5/2014 13:34  Apples      73
4/5/2014 3:41   Cherries    85
4/6/2014 12:46  Pears       14
4/8/2014 8:59   Oranges     52
4/10/2014 2:07  Apples      152
4/10/2014 18:10 Bananas      23
4/10/2014 2:40  Strawberries  98
</code>```

Code:

```<code>import pandas as pd
import numpy

df = pd.read_csv('example2.csv', header=0, dtype='unicode')
df_count = df['fruit'].value_counts()
x = 0 #starting my counter values or position in the column
df.sort_values(['fruit'], ascending=True, inplace=True) #sorting the column
fruit
print(df)
old_fruit = df.fruit[x]
new_fruit = df.fruit[x+1]
print(old_fruit)
print(new_fruit)
</code>```

答:
I believe you are still accessing the old index of x. After you sort, insert this to reindex:</p>

```<code>df.reset_index(drop=True, inplace=True)
</code>```

Title: Dataframe Sorting

Body:
I am working on Python pandas, beginning with sorting a dataframe I have created from a csv file. I am trying to create a for loop eventually, using values to compare. However, when I print the new values, they are using the original dataframe instead of the sorted version. How do I properly do the below?

Original CSV data:

date          fruit     quantity
4/5/2014 13:34  Apples      73
4/5/2014 3:41   Cherries    85
4/6/2014 12:46  Pears       14
4/8/2014 8:59   Oranges     52
4/10/2014 2:07  Apples      152
4/10/2014 18:10 Bananas      23
4/10/2014 2:40  Strawberries  98

Code:

import pandas as pd
import numpy

df = pd.read_csv('example2.csv', header=0, dtype='unicode')
df_count = df['fruit'].value_counts()
x = 0 #starting my counter values or position in the column
df.sort_values(['fruit'], ascending=True, inplace=True) #sorting the column
fruit
print(df)
old_fruit = df.fruit[x]
new_fruit = df.fruit[x+1]
print(old_fruit)
print(new_fruit)

Body:
I believe you are still accessing the old index of x. After you sort, insert this to reindex:

df.reset_index(drop=True, inplace=True)


问:
leveneTest for several variables
How can I apply leveneTest on each dependent variable seperately and after that how I can extract the P-value of each analysis and bring all the p-values in a matrix.</p>

```<code>responses <- as.matrix(mtcars[,-c(4,8,9)])
leveneTest(responses~as.factor(am)*as.factor(vs),data=mtcars)
</code>```

答:
You can try this:</p>

```<code>responses <- as.matrix(mtcars[,-c(4,8,9)])
results <- data.frame(var = colnames(responses), p = rep(NA,dim(responses)[2]))
results$p <- apply(responses,2,function(x) {leveneTest(x ~ as.factor(mtcars$am)*as.factor(mtcars$vs))[1,3]})
</code>```

Title: leveneTest for several variables

Body:
How can I apply leveneTest on each dependent variable seperately and after that how I can extract the P-value of each analysis and bring all the p-values in a matrix.

responses <- as.matrix(mtcars[,-c(4,8,9)])
leveneTest(responses~as.factor(am)*as.factor(vs),data=mtcars)

Body:
You can try this:

responses <- as.matrix(mtcars[,-c(4,8,9)])
results <- data.frame(var = colnames(responses), p = rep(NA,dim(responses)[2]))
results$p <- apply(responses,2,function(x) {leveneTest(x ~ as.factor(mtcars$am)*as.factor(mtcars$vs))[1,3]})


问:
AngularJS 1.x: Dynamically created multiple File Upload fields
You have to excuse me, I do not use Angular that often. I need to implement a solution in which I can upload files from dynamically generated input fields.

The catch is that I cannot use any directives (this is due to the framework I am using in which AngularJS is implemented).

My current code for creating fields:

```<code>$scope.addNewFile = function() {
    var newFileNo = $scope.files.length + 1;
    $scope.files.push({'id': 'file' + newFileNo});
};

$scope.removeFile = function() {
    var lastFile = $scope.files.length - 1;
    $scope.files.splice(lastFile);
};
</code>```

And here is the code for uploading files (not correct, because of static id and name values:

```<code>$scope.uploadFile = function() {
    var file = document.getElementById('file').files[0],
        r = new FileReader;
    r.onloadend = function (e) {
        var data = e.target.result;
        console.log('data');
        console.log(data);
        // http.post
    };
    r.readAsArrayBuffer(file);
};
</code>```

And here is my HTML:

```<code><div data-ng-repeat="file in files">
    <div class="row top-buffer">
        <div class="col-lg-10">
            <input type="file"
                   ng-model="file.name"
                   name="file"
                   class="form-control"
                   id="file">
        </div>
        <div class="col-lg-2 text-right">
            <div class="btn btn-primary" ng-click="uploadFile()">Upload</div>
        </div>
    </div>
</div>
<div class="row top-buffer">
    <div class="col-lg-11"></div>
    <div class="col-lg-1 text-right">
        <div class="glyphicon glyphicon-plus" aria-hidden="true" ng-click="addNewFile()"></div>
        <div class="glyphicon glyphicon-minus" aria-hidden="true" ng-click="removeFile()"></div>
    </div>
</div>
</code>```

I can't really understand how I can get the values of dynamically generated file fields... any help appreciated!

答:
There is no ng-model for <input type=file, but you can achieve what you want setting the id dynamically with ng-attr:

```<code><div ng-repeat="file in files">
  {{file.id}}:
  <input type="file"
         ng-attr-name="{{file.id}}"
         ng-attr-id="{{file.id}}">
</div>
</code>```

On uploadFile() you can post them:

```<code>$scope.uploadFile = function() {
  $scope.files.forEach(function(file) {
    // $http.post: document.getElementById(file.id).files[0])
  });
};
</code>```

Example on Fiddle: https://jsfiddle.net/virgilioafonsojr/92nw4j4f/1/

I hope it helps.

Body:
You have to excuse me, I do not use Angular that often. I need to implement a solution in which I can upload files from dynamically generated input fields.

The catch is that I cannot use any directives (this is due to the framework I am using in which AngularJS is implemented).

My current code for creating fields:

$scope.addNewFile = function() {
    var newFileNo = $scope.files.length + 1;
    $scope.files.push({'id': 'file' + newFileNo});
};

$scope.removeFile = function() {
    var lastFile = $scope.files.length - 1;
    $scope.files.splice(lastFile);
};

And here is the code for uploading files (not correct, because of static id and name values:

$scope.uploadFile = function() {
    var file = document.getElementById('file').files[0],
        r = new FileReader;
    r.onloadend = function (e) {
        var data = e.target.result;
        console.log('data');
        console.log(data);
        // http.post
    };
    r.readAsArrayBuffer(file);
};

And here is my HTML:

            <input type="file"
                   ng-model="file.name"
                   name="file"
                   class="form-control"
                   id="file">

Upload

I can't really understand how I can get the values of dynamically generated file fields... any help appreciated!

Body:
There is no ng-model for <input type=file, but you can achieve what you want setting the id dynamically with ng-attr:

<div ng-repeat="file in files">
  {{file.id}}:
  <input type="file"
         ng-attr-name="{{file.id}}"
         ng-attr-id="{{file.id}}">
</div>

On uploadFile() you can post them:

$scope.uploadFile = function() {
  $scope.files.forEach(function(file) {
    // $http.post: document.getElementById(file.id).files[0])
  });
};

Example on Fiddle: https://jsfiddle.net/virgilioafonsojr/92nw4j4f/1/

I hope it helps.


问:
Hive INSERT OVERWRITE DIRECTORY command output is not separated by a delimiter. Why?
The file that I am loading is separated by ' ' (white space). Below is the file. The file resides in HDFS:-

```<code>001 000
001 000
002 001
003 002
004 003
005 004
006 005
007 006
008 007
099 007
</code>```

1> I am creating an external table and loading the file by issuing the below command:-

```<code>CREATE EXTERNAL TABLE IF NOT EXISTS graph_edges (src_node_id STRING COMMENT 'Node ID of Source node', dest_node_id STRING COMMENT 'Node ID of Destination node') ROW FORMAT DELIMITED FIELDS TERMINATED BY ' ' STORED AS TEXTFILE LOCATION '/user/hadoop/input';
</code>```

2> After this, I am simply inserting the table in another file by issuing the below command:-

```<code>INSERT OVERWRITE DIRECTORY '/user/hadoop/output' SELECT * FROM graph_edges;
</code>```

3> Now, when I cat the file, the fields are not separated by any delimiter:-

```<code>hadoop dfs -cat /user/hadoop/output/000000_0
</code>```

Output:-

```<code>001000
001000
002001
003002
004003
005004
006005
007006
008007
099007
</code>```

Can somebody please help me out? Why is the delimiter being removed and how to delimit the output file?

In the CREATE TABLE command I tried DELIMITED BY '\t' but then I am getting unnecessary NULL column.

Any pointers help much appreciated. I am using Hive 0.9.0 version.

答:
you can use this parameter "row format delimited fields terminated by '|'" for example in your case should be

INSERT OVERWRITE DIRECTORY '/user/hadoop/output' row format delimited fields terminated by '|' SELECT * FROM graph_edges;

Body:
The file that I am loading is separated by ' ' (white space). Below is the file. The file resides in HDFS:-

001 000
001 000
002 001
003 002
004 003
005 004
006 005
007 006
008 007
099 007

1> I am creating an external table and loading the file by issuing the below command:-

CREATE EXTERNAL TABLE IF NOT EXISTS graph_edges (src_node_id STRING COMMENT 'Node ID of Source node', dest_node_id STRING COMMENT 'Node ID of Destination node') ROW FORMAT DELIMITED FIELDS TERMINATED BY ' ' STORED AS TEXTFILE LOCATION '/user/hadoop/input';

2> After this, I am simply inserting the table in another file by issuing the below command:-

INSERT OVERWRITE DIRECTORY '/user/hadoop/output' SELECT * FROM graph_edges;

3> Now, when I cat the file, the fields are not separated by any delimiter:-

hadoop dfs -cat /user/hadoop/output/000000_0

Output:-

001000
001000
002001
003002
004003
005004
006005
007006
008007
099007

Can somebody please help me out? Why is the delimiter being removed and how to delimit the output file?

In the CREATE TABLE command I tried DELIMITED BY '\t' but then I am getting unnecessary NULL column.

Any pointers help much appreciated. I am using Hive 0.9.0 version.


问:
How to ignore python modules during import?
During the build process of a Python application I need to ignore some imports (because these modules are created by the build process). It is a chicken-and-egg-question, that I can't resolve easily.
So I thought I could use the import hook to do this like this:

```<code>class ImportBlocker(object):
    def __init__(self, *args):
        self.module_names = args

    def find_module(self, fullname, path=None):
        if fullname in self.module_names:
            return self
        return None

    def load_module(self, name):
        raise ImportError("%s is blocked and cannot be imported" % name)

import sys
sys.meta_path = [ImportBlocker('chickenlib')]
</code>```

But because I raise an error the build process stop --- I just want to silently ignore the import ... returning "None" does not work, too.
Is there a way to do this?

答:
If you are working on Python 3.4 or greater than you can "silently ignore" an import by altering your example just slightly to implement an exec_module that will create an empty module.

```<code>class ImportBlocker(object):
    def __init__(self, *args):
        self.module_names = args

    def find_module(self, fullname, path=None):
        if fullname in self.module_names:
            return self
        return None

    def exec_module(self, mdl):
        # return an empty namespace
        return {}
</code>```

Now:

```<code>>>> import sys
>>> sys.meta_path = [ImportBlocker('chickenlib')]

>>> # this will work fine
>>> import chickenlib

>>> # there is nothing useful in your imported module
>>> print(vars(chickenlib))
{'__doc__': None, '__package__': '', '__name__': 'chickenlib', '__loader__': <__main__.ImportBlocker object at 0x102b8c470>, '__spec__': ModuleSpec(name='chickenlib', loader=<__main__.ImportBlocker object at 0x102b8c470>)}
</code>```

Body:
During the build process of a Python application I need to ignore some imports (because these modules are created by the build process). It is a chicken-and-egg-question, that I can't resolve easily.
So I thought I could use the import hook to do this like this:

class ImportBlocker(object):
    def __init__(self, *args):
        self.module_names = args

    def find_module(self, fullname, path=None):
        if fullname in self.module_names:
            return self
        return None

    def load_module(self, name):
        raise ImportError("%s is blocked and cannot be imported" % name)

import sys
sys.meta_path = [ImportBlocker('chickenlib')]

But because I raise an error the build process stop --- I just want to silently ignore the import ... returning "None" does not work, too.
Is there a way to do this?

Body:
If you are working on Python 3.4 or greater than you can "silently ignore" an import by altering your example just slightly to implement an exec_module that will create an empty module.

class ImportBlocker(object):
    def __init__(self, *args):
        self.module_names = args

    def find_module(self, fullname, path=None):
        if fullname in self.module_names:
            return self
        return None

    def exec_module(self, mdl):
        # return an empty namespace
        return {}

Now:

>>> import sys
>>> sys.meta_path = [ImportBlocker('chickenlib')]

>>> # this will work fine
>>> import chickenlib

>>> # there is nothing useful in your imported module
>>> print(vars(chickenlib))
{'__doc__': None, '__package__': '', '__name__': 'chickenlib', '__loader__': <__main__.ImportBlocker object at 0x102b8c470>, '__spec__': ModuleSpec(name='chickenlib', loader=<__main__.ImportBlocker object at 0x102b8c470>)}


问:
Confusing Character String Interaction
I'm currently doing the CS50 course, and I'm stuck on the credit problem. The idea is to make a program to verify cards due to their inbuilt checksum. The first step is to take every second digit and multiply it by 2, then add all the digits of the products together.

My code isn't finished, but I've set it up to print some intermediary steps just so I can see what's going on.

```<code>#include <stdio.h>
#include <string.h>

void checksum (char number[20]);

int main (void){
  char *card;

  printf("Please enter a card number:");
  scanf("%s", card);
  if (strlen(card) == 13 || strlen(card) ==  16 || strlen(card) == 15) {
    checksum(card);
  }
  else{
    printf("Not a number. Please try again.\n");
    main();
  }
}

void checksum (char *number) {

  int check = 0;
  int digits = 0;
  for(int i = 1; i < 17; i += 2){
    printf("No%c\n", number[i]);
    digits = (number[i] * 2);
    printf("D%i\n", digits);
    while (digits > 0) {
      check += digits % 10;
      printf("C%i\n", check);
      digits = digits / 10;
    }
  }
}
</code>```

I know the first part is far from perfect but it's the checksum function I'm concerned with at the moment. When it takes the second digit(5) everything is fine. But then when it's multiplied by 2 according to the next line, somehow the result is 106(?)

Can someone explain what's going on here?

terminal output

答:
You read in a string, i.e. a sequence of characters, probably in ASCII format. So your input "1500150015001500" is actually a sequence of characters terminated by string terminating character 0x0, e.g. like { '1', '5', '0', .... '\0' }. A single character value like '1', when interpreted as an integral value, is represented by its ASCII code, which is 48 for '0', 49 for '1', ... , and 53 for '5'. Hence, an expression like char c = '5'; int digit = c*2 actually yields 106 for digit. To take character '5' as integral value 5, you could write int digit = (c - '0'), which is the same as if you wrote (53 - 48).

Without modifying your code to much, test what happens:

```<code>#include <stdio.h>
#include <string.h>

void checksum (char *number);

int main (void){
  char card[30];

  printf("Please enter a card number:");
  scanf("%s", card);
  if (strlen(card) == 13 || strlen(card) ==  16 || strlen(card) == 15) {
    checksum(card);
  }
  else{
    printf("Not a number. Please try again.\n");
    main();
  }
}

void checksum (char *number) {

  int check = 0;
  int digits = 0;
  for(int i = 1; i < strlen(number); i += 2){
    printf("No%c\n", number[i]);
    digits = ((number[i]-'0') * 2);
    printf("D%i\n", digits);
    while (digits > 0) {
      check += digits % 10;
      printf("C%i\n", check);
      digits = digits / 10;
    }
  }
}
</code>```

Title: Confusing Character String Interaction

Body:
I'm currently doing the CS50 course, and I'm stuck on the credit problem. The idea is to make a program to verify cards due to their inbuilt checksum. The first step is to take every second digit and multiply it by 2, then add all the digits of the products together.

My code isn't finished, but I've set it up to print some intermediary steps just so I can see what's going on.

#include <stdio.h>
#include <string.h>

void checksum (char number[20]);

int main (void){
  char *card;

  printf("Please enter a card number:");
  scanf("%s", card);
  if (strlen(card) == 13 || strlen(card) ==  16 || strlen(card) == 15) {
    checksum(card);
  }
  else{
    printf("Not a number. Please try again.\n");
    main();
  }
}

void checksum (char *number) {

  int check = 0;
  int digits = 0;
  for(int i = 1; i < 17; i += 2){
    printf("No%c\n", number[i]);
    digits = (number[i] * 2);
    printf("D%i\n", digits);
    while (digits > 0) {
      check += digits % 10;
      printf("C%i\n", check);
      digits = digits / 10;
    }
  }
}

I know the first part is far from perfect but it's the checksum function I'm concerned with at the moment. When it takes the second digit(5) everything is fine. But then when it's multiplied by 2 according to the next line, somehow the result is 106(?)

Can someone explain what's going on here?

terminal output

Body:
You read in a string, i.e. a sequence of characters, probably in ASCII format. So your input "1500150015001500" is actually a sequence of characters terminated by string terminating character 0x0, e.g. like { '1', '5', '0', .... '\0' }. A single character value like '1', when interpreted as an integral value, is represented by its ASCII code, which is 48 for '0', 49 for '1', ... , and 53 for '5'. Hence, an expression like char c = '5'; int digit = c*2 actually yields 106 for digit. To take character '5' as integral value 5, you could write int digit = (c - '0'), which is the same as if you wrote (53 - 48).

Without modifying your code to much, test what happens:

#include <stdio.h>
#include <string.h>

void checksum (char *number);

int main (void){
  char card[30];

  printf("Please enter a card number:");
  scanf("%s", card);
  if (strlen(card) == 13 || strlen(card) ==  16 || strlen(card) == 15) {
    checksum(card);
  }
  else{
    printf("Not a number. Please try again.\n");
    main();
  }
}

void checksum (char *number) {

  int check = 0;
  int digits = 0;
  for(int i = 1; i < strlen(number); i += 2){
    printf("No%c\n", number[i]);
    digits = ((number[i]-'0') * 2);
    printf("D%i\n", digits);
    while (digits > 0) {
      check += digits % 10;
      printf("C%i\n", check);
      digits = digits / 10;
    }
  }
}


问:
Advantages of IQueryable<T> over IList<T>
In C# DAL, What advantages will i derive if i return IQueryable than IList, Iam not using Entity Framework / N Hibernate, just plain old ADO.Net.. </p>

答:
I believe returning an IQueryable allows lazy enumeration, whilst returning an IList doesn't.

If you return an IList, the query against the database is performed at the point the DAL returns the IList.  Returning an IQueryable, the return can be passed around and the query is only executated when you inspect the contents of the IQueryable.

(This is based on my experience of LINQ to SQL - but I've not checked this against a definitive source)


问:
How to reset Google Cloud Shell environment
I am trying to reset my Cloud Shell disk. I am deleting projects and creating new, but getting same cloud shell with all pre-installed files. Is there anyway to reset completely.</p>

答:
Yes there is

```<code>Restore your Cloud Shell home directory to a clean state:

Check for personal files in the home directory:
  ls -a $HOME
Remove all files from your home directory:
  sudo rm -rf $HOME
In the Cloud Shell menu, click the gear icon, then click Restart Cloud Shell. Click Restart Cloud Shell in the confirmation dialog.
</code>```

From the docs https://cloud.google.com/shell/docs/resetting-cloud-shell

Body:
Yes there is

Restore your Cloud Shell home directory to a clean state:

Check for personal files in the home directory:
  ls -a $HOME
Remove all files from your home directory:
  sudo rm -rf $HOME
In the Cloud Shell menu, click the gear icon, then click Restart Cloud Shell. Click Restart Cloud Shell in the confirmation dialog.

From the docs https://cloud.google.com/shell/docs/resetting-cloud-shell


问:
Django-paypal Heroku VS Local ? PAYPAL IPN
In my development locally the django-paypal plugin is amazing and have had ZERO issues attempting paypal and the developer account.  After pushing to heroku, i cant seem to contact the paypal server doing the exact same steps....

for example when in local development i am getting the Payment Accepted and the IPN to return to my localhost with ngrok.

once i pushed the app to heroku everything loaded and it was looking good, my problem is not i am getting a 500 error from paypal when attempting to connect to the sandbox in from heroku??

Please help,
Ryan

答:
This took me FOREVER so im posting this here for the next up and comming django dev looking to work with the django-by-example book and using heroku as a production host!

```<code>heroku addons:add cloudamqp
Adding cloudamqp on secure-fortress-6930... done, v6 (free)
Use `heroku addons:docs cloudamqp` to view documentation.

BROKER_URL = os.environ.get("CLOUDAMQP_URL", "django://")
BROKER_POOL_LIMIT = 1
BROKER_CONNECTION_MAX_RETRIES = None

CELERY_TASK_SERIALIZER = "json"
CELERY_ACCEPT_CONTENT = ["json", "msgpack"]
CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler'

if BROKER_URL == "django://":
    INSTALLED_APPS += ("kombu.transport.django",)
</code>```

Install the addon
add the code to the seetings.py
enjoy!

https://drdaeman.github.io/heroku-djcelery-example/

Body:
This took me FOREVER so im posting this here for the next up and comming django dev looking to work with the django-by-example book and using heroku as a production host!

heroku addons:add cloudamqp
Adding cloudamqp on secure-fortress-6930... done, v6 (free)
Use `heroku addons:docs cloudamqp` to view documentation.

BROKER_URL = os.environ.get("CLOUDAMQP_URL", "django://")
BROKER_POOL_LIMIT = 1
BROKER_CONNECTION_MAX_RETRIES = None

CELERY_TASK_SERIALIZER = "json"
CELERY_ACCEPT_CONTENT = ["json", "msgpack"]
CELERYBEAT_SCHEDULER = 'djcelery.schedulers.DatabaseScheduler'

if BROKER_URL == "django://":
    INSTALLED_APPS += ("kombu.transport.django",)

Install the addon
add the code to the seetings.py
enjoy!

https://drdaeman.github.io/heroku-djcelery-example/


问:
React JS memoization on list items
If I have a simple app, something like this:

```<code>function renderRow(company) {
return DOM.li({
        className: 'item'
    },
    company.title);
}

function renderApp(companies) {
  return DOM.ul({
        className: 'list'
    },
    companies.sort(function(a, b) {
        return a.votes - b.votes;
    }).map(renderRow))
}
var appModel = getCompaniesJSON(100);
renderComponent(renderApp(appModel), document.body);
</code>```

And I would not want to rerender every list item when a title of a company hasn't changed - is there a way of implementing a shouldComponentUpdate function for the rows(li items)?

答:
It can be done by moving the output of renderRow to a separate <Row title={company.title} /> component. Then you would be able to use shouldComponentUpdate for each row item checking whether or not the prop title has changed:

In <Row/> component:

```<code>shouldComponentUpdate(nextProps, nextState){
    return nextProps.title !== this.props.title;
}
</code>```

Title: React JS memoization on list items

Body:
If I have a simple app, something like this:

function renderRow(company) {
return DOM.li({
        className: 'item'
    },
    company.title);
}

function renderApp(companies) {
  return DOM.ul({
        className: 'list'
    },
    companies.sort(function(a, b) {
        return a.votes - b.votes;
    }).map(renderRow))
}
var appModel = getCompaniesJSON(100);
renderComponent(renderApp(appModel), document.body);

And I would not want to rerender every list item when a title of a company hasn't changed - is there a way of implementing a shouldComponentUpdate function for the rows(li items)?

Body:
It can be done by moving the output of renderRow to a separate <Row title={company.title} /> component. Then you would be able to use shouldComponentUpdate for each row item checking whether or not the prop title has changed:

In <Row/> component:

shouldComponentUpdate(nextProps, nextState){
    return nextProps.title !== this.props.title;
}


问:
invalid qualifier error when defining variable for worksheet
I want to define Sheeet1 in the current workbook.  The name of the workbook is dynamic. this code gives me an "invalid qualifier" error

```<code>   Dim ws1 As Worksheet
    Set ws1 = ActiveWorkbook.Name.Sheets("Sheet1")
</code>```

thanks in advance for the help and sorry if it's obvious and I am just not seeing it.

答:
dont use name - use this</p>

```<code>Dim ws1 As Worksheet
Set ws1 = ActiveWorkbook.Sheets("Sheet1")
</code>```

Body:
I want to define Sheeet1 in the current workbook.  The name of the workbook is dynamic. this code gives me an "invalid qualifier" error

   Dim ws1 As Worksheet
    Set ws1 = ActiveWorkbook.Name.Sheets("Sheet1")

thanks in advance for the help and sorry if it's obvious and I am just not seeing it.

Body:
dont use name - use this

Dim ws1 As Worksheet
Set ws1 = ActiveWorkbook.Sheets("Sheet1")


问:
Why is setting empty text node in XML not an error?
Example input:

```<code> <p>    </p>
</code>```

Example code:

```<code> // assume node is the 'p' Element, then chNode is a text node
 chNode = node.getFirstChild();

 // set text to empty string
 chNode.setNodeValue("");
</code>```

I would have thought setting empty text is an error, or, it would delete the text node.

Since, we have a p element with an empty text node.  However, if we had deleted the text node instead, would it not be the same thing?

I'm trying to understand the purpose of the empty text node.

答:
I would have thought setting empty text is an error, or, it would delete the text node.

There is no error, since it is still a valid document.

However, if we had deleted the text node instead, would it not be the same thing?

No. In a structural manner, an empty element is different from a deleted element.

I'm trying to understand the purpose of the empty text node.

An empty element doesn't have meaning by itself. Who gives meaning is the person or application that makes use of the XML document.

These three documents are syntactically different from one another:

<root></root>
```

<pre class="lang-xml prettyprint-override"><code><root><p></p></root>
</code>```

<root>

</root>
```

For a given purpose they may mean the same, but as for the XML specification, which defines the syntax of XML, they are different.

Body:
Example input:

Example code:

 // assume node is the 'p' Element, then chNode is a text node
 chNode = node.getFirstChild();

 // set text to empty string
 chNode.setNodeValue("");

I would have thought setting empty text is an error, or, it would delete the text node.

Since, we have a p element with an empty text node.  However, if we had deleted the text node instead, would it not be the same thing?

I'm trying to understand the purpose of the empty text node.

Body:
I would have thought setting empty text is an error, or, it would delete the text node.

There is no error, since it is still a valid document.

However, if we had deleted the text node instead, would it not be the same thing?

No. In a structural manner, an empty element is different from a deleted element.

I'm trying to understand the purpose of the empty text node.

An empty element doesn't have meaning by itself. Who gives meaning is the person or application that makes use of the XML document.

These three documents are syntactically different from one another:

<root></root>

<root><p></p></root>

<root><p>    </p></root>

For a given purpose they may mean the same, but as for the XML specification, which defines the syntax of XML, they are different.


问:
Fragment oriented architecture and the back stack
I am learning how to implement a "single activity - multiple fragments" architecture. It is widespread approach nowadays as I understand and you can find a lot of articles on this topic. For example this one http://vinsol.com/blog/2014/09/15/advocating-fragment-oriented-applications-in-android/.

There are two types of fragments in such architecture - parent and child from my point of view.

Parent fragment is started from the top level, from a drawer for example. I prefer to do it in the following manner:

```<code>public void startParent(Fragment fragment) {
    manager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
    FragmentTransaction transaction = manager.beginTransaction();
    transaction.replace(R.id.fragment_container, fragment);
    transaction.addToBackStack(fragment.getClass().getCanonicalName());
    transaction.commit();
}
</code>```

Also, there is child fragment that is started like this:

```<code>public void startChild(Fragment fragment) {
    FragmentTransaction transaction = manager.beginTransaction();
    transaction.replace(R.id.fragment_container, fragment);
    transaction.addToBackStack(fragment.getClass().getCanonicalName());
    transaction.commit();
}
</code>```

In both cases, the manager is standard fragment manager provided by activity.
There is only one difference between the provided methods. In the first case back stack is cleared to start new fragment from scratch. On the seconds one, it just pushed to the back stack.

As a result back stack may look like:
Parent -> Child1 -> Child2

A user navigates between fragments or just start the new sequence from the top level (drawer).

When a user presses back button the last fragment is popped back from the stack. As I understand you even don't need to override onBackPressed() method of activity.

It works fine until screen configuration is changed. When screen configuration is changed onBackPressed() leads to well-known error java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

There are a lot of questions have been asked already about this issue on StackOverflow but I didn't find the right answer for my case.  People suggest to call commitAllowingStateLoss() and so on but it is unrelated to my case. I do not want to start new fragment I just want to go back to previous one.

So my question is following: is my understanding correct that there is no way to navigate back through back stack after screen configuration change? All you have to do is invalidate it and start from scratch?

答:
Such an exception occurs when you try to perform a fragment transition after your fragment activity's onSaveInstanceState() gets called.

After configuration is changed, system reclaims the activity for resources and recreates it later, that's why fragment will not create and  java.lang.IllegalStateException exception is shown.

Reference :- getting exception "IllegalStateException: Can not perform this action after onSaveInstanceState"

Body:
I am learning how to implement a "single activity - multiple fragments" architecture. It is widespread approach nowadays as I understand and you can find a lot of articles on this topic. For example this one http://vinsol.com/blog/2014/09/15/advocating-fragment-oriented-applications-in-android/.

There are two types of fragments in such architecture - parent and child from my point of view.

Parent fragment is started from the top level, from a drawer for example. I prefer to do it in the following manner:

public void startParent(Fragment fragment) {
    manager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
    FragmentTransaction transaction = manager.beginTransaction();
    transaction.replace(R.id.fragment_container, fragment);
    transaction.addToBackStack(fragment.getClass().getCanonicalName());
    transaction.commit();
}

Also, there is child fragment that is started like this:

public void startChild(Fragment fragment) {
    FragmentTransaction transaction = manager.beginTransaction();
    transaction.replace(R.id.fragment_container, fragment);
    transaction.addToBackStack(fragment.getClass().getCanonicalName());
    transaction.commit();
}

In both cases, the manager is standard fragment manager provided by activity.
There is only one difference between the provided methods. In the first case back stack is cleared to start new fragment from scratch. On the seconds one, it just pushed to the back stack.

As a result back stack may look like:
Parent -> Child1 -> Child2

A user navigates between fragments or just start the new sequence from the top level (drawer).

When a user presses back button the last fragment is popped back from the stack. As I understand you even don't need to override onBackPressed() method of activity.

It works fine until screen configuration is changed. When screen configuration is changed onBackPressed() leads to well-known error java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

There are a lot of questions have been asked already about this issue on StackOverflow but I didn't find the right answer for my case.  People suggest to call commitAllowingStateLoss() and so on but it is unrelated to my case. I do not want to start new fragment I just want to go back to previous one.

So my question is following: is my understanding correct that there is no way to navigate back through back stack after screen configuration change? All you have to do is invalidate it and start from scratch?


问:
How to set default value in Eureka-Form
I am creating a series of ImageCheckRows as a SelectableSection, and I would like to set some default values.  Essentially each row returns a true/false value, so somewhere there should be a simply method of setting true or false on each row.  I tried the row.value but this requires a 'String?'

```<code>currentSection! <<< ImageCheckRow<String> { row in
   row.tag = "\(tagname)_\(optionKey)"
   row.title = optionValue as? String
   row.selectableValue = optionKey as? String

   if let dvkey = optionKey as? String {
      print("dvkey = \(dvkey)")
      if let _ = defaultValues?.value(forKey: dvkey) {
         print("we found dvkey in the defaultValues dict - try row.select")
         row.value = true
      }
   }

}.cellSetup { cell, _ in
   cell.trueImage = UIImage(named: imageChecked)!
   cell.falseImage = UIImage(named: imageUnchecked)!
}
</code>```

I also tried using the function:

```<code>row.select()
</code>```

But this didn't work either.

Then I tried moving it to the cellSetup, but this didn't work either.

Can anyone help me here?

答:
Worked it out myself...

```<code>row.value = optionKeyValue as? String
</code>```

This is a radio button style control, and as I create the row with the default radio button I set the value to the key, however it must be a string representation, even if it is numeric. Who would have guessed!

My first thought was that the radio button control is checked/unchecked, hence it should really be a true/false value.

My second thought was that the radio button control default value would be set against the group, which is a more logical place to set or change the value.

Wrong on both counts.

Title: How to set default value in Eureka-Form

Body:
I am creating a series of ImageCheckRows as a SelectableSection, and I would like to set some default values.  Essentially each row returns a true/false value, so somewhere there should be a simply method of setting true or false on each row.  I tried the row.value but this requires a 'String?'

currentSection! <<< ImageCheckRow<String> { row in
   row.tag = "\(tagname)_\(optionKey)"
   row.title = optionValue as? String
   row.selectableValue = optionKey as? String

   if let dvkey = optionKey as? String {
      print("dvkey = \(dvkey)")
      if let _ = defaultValues?.value(forKey: dvkey) {
         print("we found dvkey in the defaultValues dict - try row.select")
         row.value = true
      }
   }

}.cellSetup { cell, _ in
   cell.trueImage = UIImage(named: imageChecked)!
   cell.falseImage = UIImage(named: imageUnchecked)!
}

I also tried using the function:

row.select()

But this didn't work either.

Then I tried moving it to the cellSetup, but this didn't work either.

Can anyone help me here?

Body:
Worked it out myself...

row.value = optionKeyValue as? String

This is a radio button style control, and as I create the row with the default radio button I set the value to the key, however it must be a string representation, even if it is numeric. Who would have guessed!

My first thought was that the radio button control is checked/unchecked, hence it should really be a true/false value.

My second thought was that the radio button control default value would be set against the group, which is a more logical place to set or change the value.

Wrong on both counts.


问:
Finding highest value in range key
I have a dynamodb defined with RangeKey as time_in_millis. Now, I want to find the latest value of a given object based on the HashKey.

I am trying this

```<code>MyObject key = new MyObject();
key.setHashKey("hash_key_of_object");

DynamoDBQueryExpression<MyObject> q = new DynamoDBQueryExpression<MyObject>().withHashKeyValues(key)
</code>```

next, I am not sure how to specific to find the highest value in range key.

答:
ScanIndexForward can be used to sort the range key in descending order. The first item in the result set is the maximum value of the range key (sort key is otherwise called range key).

```<code>DynamoDBQueryExpression<MyObject> queryExpression = new DynamoDBQueryExpression<MyObject>().withHashKeyValues(myObject)
                .withScanIndexForward(false);

myObjectList = dynamoDBMapper.query(MyObject.class, queryExpression);
</code>```

If ScanIndexForward is true, DynamoDB returns the results in the order
  in which they are stored (by sort key value). This is the default
  behavior. If ScanIndexForward is false, DynamoDB reads the results in
  reverse order by sort key value, and then returns the results to the
  client.

Title: Finding highest value in range key

Body:
I have a dynamodb defined with RangeKey as time_in_millis. Now, I want to find the latest value of a given object based on the HashKey.

I am trying this

MyObject key = new MyObject();
key.setHashKey("hash_key_of_object");

DynamoDBQueryExpression<MyObject> q = new DynamoDBQueryExpression<MyObject>().withHashKeyValues(key)

next, I am not sure how to specific to find the highest value in range key.

Body:
ScanIndexForward can be used to sort the range key in descending order. The first item in the result set is the maximum value of the range key (sort key is otherwise called range key).

DynamoDBQueryExpression<MyObject> queryExpression = new DynamoDBQueryExpression<MyObject>().withHashKeyValues(myObject)
                .withScanIndexForward(false);

myObjectList = dynamoDBMapper.query(MyObject.class, queryExpression);

If ScanIndexForward is true, DynamoDB returns the results in the order
  in which they are stored (by sort key value). This is the default
  behavior. If ScanIndexForward is false, DynamoDB reads the results in
  reverse order by sort key value, and then returns the results to the
  client.


问:
Average of three biggest parameters out of five without using sorting algorithm or vector/array
I'm trying to create a function with has 5 input parameters and returns the average of the 3 biggest. However I'm not supposed to use a sorting algorithm, vector/arrays or function libraries and still try to use to develop the most efficient logic possible.

So far I've come up with the code below. Is it the most efficient possible considering the restrictions?

```<code>float avg3of5(float a, float b, float c, float d, float e) {
    float min;
    float min2;

    min = a;
    if (b < min) {
        min2 = min;
        min = b;
    }
    else {
    min2 = b;
    }

    if (c < min) {
        min2 = min;
        min = c;
    }
    else {
        if (c < min2) {
            min2 = c;
        }
    }

    if (d < min) {
        min2 = min;
        min = d;
    }
    else {
        if (d < min2) {
            min2 = d;
        }
    }

    if (e < min) {
        min2 = min;
        min = e;
    }
    else {
        if (e < min2) {
            min2 = e;
        }
    }

    Return = (a + b + c + d + e - min - min2) / 3
}
</code>```

答:
One thing that immediately jumps out at me is the repetition caused by:

```<code>if (b < min) {
    min2 = min;
    min = b;
}
else {
    min2 = b;
}
</code>```

It may be better to extract this logic into a function and then call it instead:

```<code>#include <iostream>

float avg3of5(const float, const float, const float, const float, const float);
void adjustmins(const float, float*, float*);

int main()
{
    std::cout << avg3of5(4,6,2,6,3);
}

float avg3of5(const float a, const float b, const float c, const float d, const float e){
    float min;
    float min2;

    min = a;

    adjustmins(b, &min, &min2);
    adjustmins(c, &min, &min2);
    adjustmins(d, &min, &min2);
    adjustmins(e, &min, &min2);

    return (a + b + c + d + e - min - min2) / 3;
}

void adjustmins(const float n, float* min, float* min2){
    if (n < *min) {
        *min2 = *min;
        *min = n;
    }
    else {
        *min2 = n;
    }
}
</code>```

I can't tell you if this is more efficient in terms of processing time, but there's much less repetition.

If you'd prefer to use references rather than pointers use this (C++ only):

```<code>void adjustmins(const float, float&, float&);
</code>```

and

```<code>void adjustmins(const float n, float& min, float& min2){
    if (n < min) {
        min2 = min;
        min = n;
    }
    else {
        min2 = n;
    }
}
</code>```

then call with:

```<code>adjustmins(b, min, min2);
</code>```

Body:
I'm trying to create a function with has 5 input parameters and returns the average of the 3 biggest. However I'm not supposed to use a sorting algorithm, vector/arrays or function libraries and still try to use to develop the most efficient logic possible.

So far I've come up with the code below. Is it the most efficient possible considering the restrictions?

float avg3of5(float a, float b, float c, float d, float e) {
    float min;
    float min2;

    min = a;
    if (b < min) {
        min2 = min;
        min = b;
    }
    else {
    min2 = b;
    }

    if (c < min) {
        min2 = min;
        min = c;
    }
    else {
        if (c < min2) {
            min2 = c;
        }
    }

    if (d < min) {
        min2 = min;
        min = d;
    }
    else {
        if (d < min2) {
            min2 = d;
        }
    }

    if (e < min) {
        min2 = min;
        min = e;
    }
    else {
        if (e < min2) {
            min2 = e;
        }
    }

    Return = (a + b + c + d + e - min - min2) / 3
}

Body:
One thing that immediately jumps out at me is the repetition caused by:

if (b < min) {
    min2 = min;
    min = b;
}
else {
    min2 = b;
}

It may be better to extract this logic into a function and then call it instead:

#include <iostream>

float avg3of5(const float, const float, const float, const float, const float);
void adjustmins(const float, float*, float*);

int main()
{
    std::cout << avg3of5(4,6,2,6,3);
}

float avg3of5(const float a, const float b, const float c, const float d, const float e){
    float min;
    float min2;

    min = a;

    adjustmins(b, &min, &min2);
    adjustmins(c, &min, &min2);
    adjustmins(d, &min, &min2);
    adjustmins(e, &min, &min2);

    return (a + b + c + d + e - min - min2) / 3;
}

void adjustmins(const float n, float* min, float* min2){
    if (n < *min) {
        *min2 = *min;
        *min = n;
    }
    else {
        *min2 = n;
    }
}

I can't tell you if this is more efficient in terms of processing time, but there's much less repetition.

If you'd prefer to use references rather than pointers use this (C++ only):

void adjustmins(const float, float&, float&);

and

void adjustmins(const float n, float& min, float& min2){
    if (n < min) {
        min2 = min;
        min = n;
    }
    else {
        min2 = n;
    }
}

then call with:

adjustmins(b, min, min2);


问:
How to tell if a string contains a certain character in JavaScript?
I have a page with a textbox where a user is supposed to enter a 24 character (letters and numbers, case insensitive) registration code.  I used maxlength to limit the user to entering 24 characters.

The registration codes are typically given as groups of characters separated by dashes, but I would like for the user to enter the codes without the dashes.

How can I write my JavaScript code without jQuery to check that a given string that the user inputs does not contain dashes, or better yet, only contains alphanumeric characters?

答:
To test for alphanumeric characters only:

```<code>if (/^[0-9A-Za-z]+$/.test(yourString))
{
    //there are only alphanumeric characters
}
else
{
    //it contains other characters
}
</code>```

The regex is testing for 1 or more (+) of the set of characters 0-9, A-Z, and a-z, starting with the beginning of input (^) and stopping with the end of input ($).

Body:
To test for alphanumeric characters only:

if (/^[0-9A-Za-z]+$/.test(yourString))
{
    //there are only alphanumeric characters
}
else
{
    //it contains other characters
}

The regex is testing for 1 or more (+) of the set of characters 0-9, A-Z, and a-z, starting with the beginning of input (^) and stopping with the end of input ($).


问:
SQLCMD Session Run SQL Script
I'm still pretty new to SQL Server but have a ton of experience with Oracle. How do I run a SQL script while I'm inside a SQLCMD session? Is their something analogous to "SQL>@C:[mypath]\myscript.sql" (Oracle) for SQL Server?

I'm sick of opening scripts and running them using bloated SQL Server Studio.

答:
sqlcmd -i file executes a file.

Can't recommend enough to check all the options in the docs.

Title: SQLCMD Session Run SQL Script


问:
Understanding 'echo' service example API from Servant paper
The introduction of the servant paper contains the following example API type:

```<code>type Echo = "echo"
          :> ReqBody ’[PlainText] String
          :> Get ’[PlainText] String
</code>```

I am attempting to understand this example. It appears to be defining a type synonym, but seems to involve some things that I have not seen before.

Here are three questions that I have about it:

How is there a string literal in the definition of a type?

"echo" is a string literal. I thought these were only used to define specific strings and don't know what this means when used in a type declaration.

What is the symbol :>?

The definition of this symbol in the 'servant' package appears to be defined here and looks like this:

```<code>data (path :: k) :> a
    deriving (Typeable)
infixr 9 :>
</code>```

I would guess that :> corresponds to a / in an api string, but do not see how this definition would make that happen.

This is the first time I am seeing a non-alphanumeric type other than  the function type ->.

What does the apostrophe before the list type mean?

[PlainText] I would understand to simply represent a list of PlainText elements, but in contrast I do not understand what ’[PlainText] means.

答:
How is there a string literal in the definition of a type?

The DataKinds extension lets you use these string literals in type signatures. Each one of them represents a different type. They all belong to the kind Symbol; we can test this using the :kind command in ghci:

```<code>Prelude> :set -XDataKinds
Prelude> :kind "foo"
"foo" :: GHC.Types.Symbol
</code>```

Because in Haskell only types of kind * have values, these type-level strings are not inhabited. But there are functions that let you obtain the corresponding term-level string anyway.

What is the symbol :>?

The TypeOperators extension lets you define types with operator names. This is useful for parameterized types that are mostly used to combine other types. Notice that :> has two  type parameters but no value-level constructors: it is only used at the type level.

What does the apostrophe before the list type mean?

DataKinds does more than enabling symbols. It lets you use value constructors as types, and the types of these constructors become kinds in its turn. For example:

```<code>Prelude> :set -XDataKinds
Prelude> :kind True
True :: Bool
</code>```

These promoted constructors are not inhabited by any term (because they have kinds other than *).

In particular, we can promote lists to the type-level. But this creates some ambiguity. What is [Int] in a signature? Is it the type of lists of Ints (that has kind *) or is it a type-level list with one element, the type Int? The apostrophe makes clear that we are talking about the type-level list.

```<code>Prelude> :set -XDataKinds
Prelude> :kind [Int]
[Int] :: *
Prelude> :kind '[Int]
'[Int] :: [*]
Prelude> :kind '[True]
'[True] :: [Bool]
</code>```

Type-level lists of more than one element don't require the apostrophe, because there's no ambiguity:

```<code>Prelude> :kind [Int,Int]
[Int,Int] :: [*]
</code>```

Body:
The introduction of the servant paper contains the following example API type:

type Echo = "echo"
          :> ReqBody ’[PlainText] String
          :> Get ’[PlainText] String

I am attempting to understand this example. It appears to be defining a type synonym, but seems to involve some things that I have not seen before.

Here are three questions that I have about it:

How is there a string literal in the definition of a type?

"echo" is a string literal. I thought these were only used to define specific strings and don't know what this means when used in a type declaration.

What is the symbol :>?

The definition of this symbol in the 'servant' package appears to be defined here and looks like this:

data (path :: k) :> a
    deriving (Typeable)
infixr 9 :>

I would guess that :> corresponds to a / in an api string, but do not see how this definition would make that happen.

This is the first time I am seeing a non-alphanumeric type other than  the function type ->.

What does the apostrophe before the list type mean?

[PlainText] I would understand to simply represent a list of PlainText elements, but in contrast I do not understand what ’[PlainText] means.

Body:
How is there a string literal in the definition of a type?

The DataKinds extension lets you use these string literals in type signatures. Each one of them represents a different type. They all belong to the kind Symbol; we can test this using the :kind command in ghci:

Prelude> :set -XDataKinds
Prelude> :kind "foo"
"foo" :: GHC.Types.Symbol

Because in Haskell only types of kind * have values, these type-level strings are not inhabited. But there are functions that let you obtain the corresponding term-level string anyway.

What is the symbol :>?

The TypeOperators extension lets you define types with operator names. This is useful for parameterized types that are mostly used to combine other types. Notice that :> has two  type parameters but no value-level constructors: it is only used at the type level.

What does the apostrophe before the list type mean?

DataKinds does more than enabling symbols. It lets you use value constructors as types, and the types of these constructors become kinds in its turn. For example:

Prelude> :set -XDataKinds
Prelude> :kind True
True :: Bool

These promoted constructors are not inhabited by any term (because they have kinds other than *).

In particular, we can promote lists to the type-level. But this creates some ambiguity. What is [Int] in a signature? Is it the type of lists of Ints (that has kind *) or is it a type-level list with one element, the type Int? The apostrophe makes clear that we are talking about the type-level list.

Prelude> :set -XDataKinds
Prelude> :kind [Int]
[Int] :: *
Prelude> :kind '[Int]
'[Int] :: [*]
Prelude> :kind '[True]
'[True] :: [Bool]

Type-level lists of more than one element don't require the apostrophe, because there's no ambiguity:

Prelude> :kind [Int,Int]
[Int,Int] :: [*]


问:
Why I couldn't sign in Android Studio for firebase?
Am trying to log in the  Android Studio for firebase creation but I couldn't sign in it's showing the popup message please sign via the opened browser and loading as long as still.

Anyone, Please solve my problem.
Thanks in Advance.

答: What is your default browser ? If chrome then change it to Firefox. This is how it worked for me</p>