问:
20s of PAGEIOLATCH_SH on Azure SQL Database with execution plan of 0.06 subtree cost
(Azure support is giving vague answers, so I'm turning to Stack Overflow with hope! :))

Situation

User complains of timeout errors on a query. I run the same query twice (same parameters) from MSMS. First run takes looong (23s or sometimes 50s), second, third, etc. runs take <1s. Execution Plans are identical and have a subtree cost of 0.0671..

The difference I do notice is a WaitStats section in the first Execution Plan with the following values:

```<code>WaitCount: 2751
WaitTimeMS: 6
WaitType: MEMORY_ALLOCATION_EXT

WaitCount: 2751
WaitTimeMS: 6
WaitType: IO_QUEUE_LIMIT

WaitCount: 669
WaitTimeMS: 20360
WaitType: PAGEIOLATCH_SH
</code>```

Azure SQL DTU is averaging around 5% max.

Azure Support says it's probably the Execution Plan compilation time. I doubt that since clearing the Proc Cache does not reintroduce the long waits after the first run.

The execution plan "leafs" are Index Seek (NonClustedred), Key Lookup (Clustered) and RID Lookup (Heap). The RID Lookup being 39% (of the 0.0671). A single row is returned (i.e. TOP 1).

3 tables are in the query with CROSS APPLY. The biggest one has 8 million rows and contains a ~40KB VARBINARY column (not referenced nor returned anywhere in the query).

Query

```<code>DECLARE @p0 VARCHAR(50); SET @p0 = '<GUID1>'

SELECT TOP 1 p.Id, p.DateCreatedUtc, p.PreviousOwnerId
FROM (
    -- last project save
    SELECT ps.Id AS psId, p.*
    FROM Projects p
    CROSS APPLY (
      SELECT TOP 1 *
      FROM ProjectSaves
      WHERE ProjectId = p.Id
      ORDER BY LastModifiedUtc DESC
    ) AS ps
    WHERE p.OwnerId = @p0
) p
CROSS APPLY (
    SELECT TOP 1 *
    FROM ProjectSavePhotos
    WHERE ProjectSaveId = p.psId AND (name LIKE 'uploads%')
) ps
WHERE P.IsDeleted = 0 AND p.Id NOT IN ('<GUID2>')
ORDER BY p.DateCreatedUtc DESC
</code>```

p.OwnerId is indexed and Azure automatically created two more indexes:

on OwnerId and Id and

on IsDeleted, OwnerId and Id

ps.ProjectId is indexed and includes LastModifiedUtc

psp.ProjectSaveId is indexed and includes name

Question

How can I diagnose the root cause of the 20s PAGEIOLATCH_SH? Could it be the mere presence of the VARBINARY column? If so, how can I confirm that?

References read

https://www.sqlshack.com/handling-excessive-sql-server-pageiolatch_sh-wait-types/

https://sqlperformance.com/2014/06/io-subsystem/knee-jerk-waits-pageiolatch-sh

答:
Unless I'm missing something this sounds normal, but I'd have to see the execution plan.  You probably want to get rid of that Key Lookup.  Is the Key Lookup grabbing a column that's missing from the index used in the Index Seek?  If yes, add it to the index in the Index Seek and see what happens.  A cross apply with such a large table can eat up a lot of buffer space, depending on how wide it is, but without seeing the query I can't say if there's a better way to get your data.
This might help as well:
https://stackoverflow.com/a/17572392/163072

Adding a clustered PK to ProjectSaves could also make a big difference.

Body:
(Azure support is giving vague answers, so I'm turning to Stack Overflow with hope! :))

Situation

User complains of timeout errors on a query. I run the same query twice (same parameters) from MSMS. First run takes looong (23s or sometimes 50s), second, third, etc. runs take <1s. Execution Plans are identical and have a subtree cost of 0.0671..

The difference I do notice is a WaitStats section in the first Execution Plan with the following values:

WaitCount: 2751
WaitTimeMS: 6
WaitType: MEMORY_ALLOCATION_EXT

WaitCount: 2751
WaitTimeMS: 6
WaitType: IO_QUEUE_LIMIT

WaitCount: 669
WaitTimeMS: 20360
WaitType: PAGEIOLATCH_SH

Azure SQL DTU is averaging around 5% max.

Azure Support says it's probably the Execution Plan compilation time. I doubt that since clearing the Proc Cache does not reintroduce the long waits after the first run.

The execution plan "leafs" are Index Seek (NonClustedred), Key Lookup (Clustered) and RID Lookup (Heap). The RID Lookup being 39% (of the 0.0671). A single row is returned (i.e. TOP 1).

3 tables are in the query with CROSS APPLY. The biggest one has 8 million rows and contains a ~40KB VARBINARY column (not referenced nor returned anywhere in the query).

Query

DECLARE @p0 VARCHAR(50); SET @p0 = '<GUID1>'

SELECT TOP 1 p.Id, p.DateCreatedUtc, p.PreviousOwnerId
FROM (
    -- last project save
    SELECT ps.Id AS psId, p.*
    FROM Projects p
    CROSS APPLY (
      SELECT TOP 1 *
      FROM ProjectSaves
      WHERE ProjectId = p.Id
      ORDER BY LastModifiedUtc DESC
    ) AS ps
    WHERE p.OwnerId = @p0
) p
CROSS APPLY (
    SELECT TOP 1 *
    FROM ProjectSavePhotos
    WHERE ProjectSaveId = p.psId AND (name LIKE 'uploads%')
) ps
WHERE P.IsDeleted = 0 AND p.Id NOT IN ('<GUID2>')
ORDER BY p.DateCreatedUtc DESC

p.OwnerId is indexed and Azure automatically created two more indexes:

on OwnerId and Id and

on IsDeleted, OwnerId and Id

ps.ProjectId is indexed and includes LastModifiedUtc

psp.ProjectSaveId is indexed and includes name

Question

How can I diagnose the root cause of the 20s PAGEIOLATCH_SH? Could it be the mere presence of the VARBINARY column? If so, how can I confirm that?

References read

https://www.sqlshack.com/handling-excessive-sql-server-pageiolatch_sh-wait-types/

https://sqlperformance.com/2014/06/io-subsystem/knee-jerk-waits-pageiolatch-sh


来源: stackexchange

问:
How to remove nested keys from a hash list in Rails
I am now trying for some hours to remove a nested hash key of a hash list.
I saw many solution non-nested hashs wich looks like this:

```<code>   sample_hash = {"key1" => "value1", "key2" => "value2"}
   sample_hash.except("key1")
</code>```

This results in:

```<code>  {"key2"=>"value2"}
</code>```

But if I try to use the except method on a hash with nested key then it doesn't work.
Here my code:

```<code>  nested_hash = {"key1"=>"value1", "key2"=>{
                                           "nested_key1"=>"nestedvalue1",
                                           "nested_key2"=>"nestedvalue2"
                                           }
                }

  nested_hash.except("nested_key2")
</code>```

The except() method returns the nested_hash without any changes. I have looked for a solution how I can pass nested hash-keys to the except method, but couldn't find anything. Is it even possible to pass nested keys to this method or should I use some other method which deletes a nested hash key from my hash list?

答:
The accepted solution is valid for the scenario given but if you're looking for something that will do this for arbitrarily nested hash tables then you're going to need a recursive solution. I couldn't find a suitable solution anywhere, so I wrote one here.

Reproduced here with annotations:

```<code>class Hash
  def except_nested(key)
    r = Marshal.load(Marshal.dump(self)) # deep copy the hashtable
    r.except_nested!(key)
  end

  def except_nested!(key)
    self.except!(key)
    self.each do |_, v| # essentially dfs traversal calling except!
      v.except_nested!(key) if v.is_a?(Hash)
    end
  end
end
</code>```

adding it to the Hash class so that you can call it the same way you call except/except! anywhere else.

```<code>t = { a: '1', b: { c: '3', d: '4' } }

r = t.except_nested(:c)
# r => {:a=>"1", :b=>{:d=>"4"}}
# t => {:a=>"1", :b=>{:c=>"3", :d=>"4"}}

t.except_nested!(:c)
# t => {:a=>"1", :b=>{:d=>"4"}}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am now trying for some hours to remove a nested hash key of a hash list.
I saw many solution non-nested hashs wich looks like this:

   sample_hash = {"key1" => "value1", "key2" => "value2"}
   sample_hash.except("key1")

This results in:

  {"key2"=>"value2"}

But if I try to use the except method on a hash with nested key then it doesn't work.
Here my code:

  nested_hash = {"key1"=>"value1", "key2"=>{
                                           "nested_key1"=>"nestedvalue1",
                                           "nested_key2"=>"nestedvalue2"
                                           }
                }

  nested_hash.except("nested_key2")

The except() method returns the nested_hash without any changes. I have looked for a solution how I can pass nested hash-keys to the except method, but couldn't find anything. Is it even possible to pass nested keys to this method or should I use some other method which deletes a nested hash key from my hash list?

Body:
The accepted solution is valid for the scenario given but if you're looking for something that will do this for arbitrarily nested hash tables then you're going to need a recursive solution. I couldn't find a suitable solution anywhere, so I wrote one here.

Reproduced here with annotations:

class Hash
  def except_nested(key)
    r = Marshal.load(Marshal.dump(self)) # deep copy the hashtable
    r.except_nested!(key)
  end

  def except_nested!(key)
    self.except!(key)
    self.each do |_, v| # essentially dfs traversal calling except!
      v.except_nested!(key) if v.is_a?(Hash)
    end
  end
end

adding it to the Hash class so that you can call it the same way you call except/except! anywhere else.

t = { a: '1', b: { c: '3', d: '4' } }

r = t.except_nested(:c)
# r => {:a=>"1", :b=>{:d=>"4"}}
# t => {:a=>"1", :b=>{:c=>"3", :d=>"4"}}

t.except_nested!(:c)
# t => {:a=>"1", :b=>{:d=>"4"}}


问:
Pivot table borders fail when expanding table in VBA
I have made a pivot table using VBA. Here is my code.

```<code> .PivotTables(1).PivotFields("Fineline").ShowDetail = False

 'Create Borders

Range("A2:K2").BorderAround Weight:=xlMedium
Range(.Range("A1"), .Range("K" & .Range("K" & Rows.Count).End(xlUp).Row)).BorderAround Weight:=xlMedium
Range(.Range("B1"), .Range("B" & .Range("B" & Rows.Count).End(xlUp).Row)).BorderAround Weight:=xlMedium
Range(.Range("C1"), .Range("E" & .Range("E" & Rows.Count).End(xlUp).Row)).BorderAround Weight:=xlMedium
Range(.Range("F1"), .Range("H" & .Range("H" & Rows.Count).End(xlUp).Row)).BorderAround Weight:=xlMedium
Range(.Range("I1"), .Range("K" & .Range("K" & Rows.Count).End(xlUp).Row)).BorderAround Weight:=xlMedium
</code>```

My pivot table is in tabular form so I am able to open and close certain tabs hence the first line of code to not show the detail. As you can see, I want to create a border around column C to E, F to H, and I to J). When I run the code, the table looks how it is supposed to. However, when I open a tab in the pivot table, all of my columns now have a border around it. I cannot figure out why the borders are doing this?

Thanks,

G

答:
PivotTables have 'Styles' that you can copy and amend. So you don't need to do this with VBA, but rather duplicate a style that looks something like you want, and make any changes you want, and it will be reapplied automatically.

To do this, right-click over a style in the Styles gallery and select Duplicate...:

...and then give it a name, and then click on any of the areas that you want to format differently:

For instance, if you want a border around the entire PivotTable, select Whole Table and then click the Format button, and select Border from the tab at the top of the dialog and then apply the formatting you want:

Then click OK to close the dialogs. The PivotTable will still look the same at this stage, because while you have set up a new Style, you haven't yet applied it to this PivotTable. So go back to the Styles gallery, click on the down arrow, and select your new PivotTable stlye from the Custom area:

Body:
I have made a pivot table using VBA. Here is my code.

 .PivotTables(1).PivotFields("Fineline").ShowDetail = False

 'Create Borders

Range("A2:K2").BorderAround Weight:=xlMedium
Range(.Range("A1"), .Range("K" & .Range("K" & Rows.Count).End(xlUp).Row)).BorderAround Weight:=xlMedium
Range(.Range("B1"), .Range("B" & .Range("B" & Rows.Count).End(xlUp).Row)).BorderAround Weight:=xlMedium
Range(.Range("C1"), .Range("E" & .Range("E" & Rows.Count).End(xlUp).Row)).BorderAround Weight:=xlMedium
Range(.Range("F1"), .Range("H" & .Range("H" & Rows.Count).End(xlUp).Row)).BorderAround Weight:=xlMedium
Range(.Range("I1"), .Range("K" & .Range("K" & Rows.Count).End(xlUp).Row)).BorderAround Weight:=xlMedium

My pivot table is in tabular form so I am able to open and close certain tabs hence the first line of code to not show the detail. As you can see, I want to create a border around column C to E, F to H, and I to J). When I run the code, the table looks how it is supposed to. However, when I open a tab in the pivot table, all of my columns now have a border around it. I cannot figure out why the borders are doing this?

Thanks,

G


问:
How to query as GROUP BY in Django?
I query a model:

```<code>Members.objects.all()
</code>```

And it returns:

```<code>Eric, Salesman, X-Shop
Freddie, Manager, X2-Shop
Teddy, Salesman, X2-Shop
Sean, Manager, X2-Shop
</code>```

What I want is to know the best Django way to fire
a group_by query to my database, like:

```<code>Members.objects.all().group_by('designation')
</code>```

Which doesn't work, of course.
I know we can do some tricks on django/db/models/query.py, but I am just curious to know how to do it without patching.

答:
You can also use the regroup template tag to group by attributes. From the docs:

```<code>cities = [
    {'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'},
    {'name': 'Calcutta', 'population': '15,000,000', 'country': 'India'},
    {'name': 'New York', 'population': '20,000,000', 'country': 'USA'},
    {'name': 'Chicago', 'population': '7,000,000', 'country': 'USA'},
    {'name': 'Tokyo', 'population': '33,000,000', 'country': 'Japan'},
]

...

{% regroup cities by country as countries_list %}

<ul>
    {% for country in countries_list %}
        <li>{{ country.grouper }}
            <ul>
            {% for city in country.list %}
                <li>{{ city.name }}: {{ city.population }}</li>
            {% endfor %}
            </ul>
        </li>
    {% endfor %}
</ul>
</code>```

Looks like this:

India

Mumbai: 19,000,000

Calcutta: 15,000,000

USA

New York: 20,000,000

Chicago: 7,000,000

Japan

Tokyo: 33,000,000

It also works on QuerySets I believe.

source: https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#regroup

edit: note the regroup tag does not work as you would expect it to if your list of dictionaries is not key-sorted. It works iteratively. So sort your list (or query set) by the key of the grouper before passing it to the regroup tag.

OwnerDisplayName: taurean

ContentLicense: CC BY-SA 4.0

Title: How to query as GROUP BY in Django?

Body:
I query a model:

Members.objects.all()

And it returns:

Eric, Salesman, X-Shop
Freddie, Manager, X2-Shop
Teddy, Salesman, X2-Shop
Sean, Manager, X2-Shop

What I want is to know the best Django way to fire
a group_by query to my database, like:

Members.objects.all().group_by('designation')

Which doesn't work, of course.
I know we can do some tricks on django/db/models/query.py, but I am just curious to know how to do it without patching.

LastEditorDisplayName: Ólafur Waage

Body:
You can also use the regroup template tag to group by attributes. From the docs:

cities = [
    {'name': 'Mumbai', 'population': '19,000,000', 'country': 'India'},
    {'name': 'Calcutta', 'population': '15,000,000', 'country': 'India'},
    {'name': 'New York', 'population': '20,000,000', 'country': 'USA'},
    {'name': 'Chicago', 'population': '7,000,000', 'country': 'USA'},
    {'name': 'Tokyo', 'population': '33,000,000', 'country': 'Japan'},
]

...

{% regroup cities by country as countries_list %}

<ul>
    {% for country in countries_list %}
        <li>{{ country.grouper }}
            <ul>
            {% for city in country.list %}
                <li>{{ city.name }}: {{ city.population }}</li>
            {% endfor %}
            </ul>
        </li>
    {% endfor %}
</ul>

Looks like this:

India

Mumbai: 19,000,000

Calcutta: 15,000,000

USA

New York: 20,000,000

Chicago: 7,000,000

Japan

Tokyo: 33,000,000

It also works on QuerySets I believe.

source: https://docs.djangoproject.com/en/2.1/ref/templates/builtins/#regroup

edit: note the regroup tag does not work as you would expect it to if your list of dictionaries is not key-sorted. It works iteratively. So sort your list (or query set) by the key of the grouper before passing it to the regroup tag.


问:
How should I convert a list into 2-D int[][] array?
```<code>private ArrayList<ArrayList<Integer>> list ;
 int size = list.size();

         int[][] iArray = new int[size][size];
for (int i=0; i<size; ++i){
             for (j = 0; j<size; ++j){
                 iArray[i][j] = list.get(j +( list.size() * i));
     }
}
</code>```

I'm using the following code but it gives me error. please suggest.

答:
What error are you getting?
the problem could be that your inner ArrayList is smaler then the outer one.
the other way around it wouldnt cause an error but your 2D Array would be incomplete.
and you have an syntax error in the inner for loop your j doenst have an variable type
you have to do something like this </p>

```<code>    int iOuterSize = list.size();
    int iBiggestInnerSize = -1;
    for (ArrayList<Integer> arrayList : list) {
        int iCurInnerSize = arrayList.size();
        if (iCurInnerSize > iBiggestInnerSize) {
            iBiggestInnerSize = iCurInnerSize;
        }
    }
    int[][] iArray = new int[iOuterSize][iBiggestInnerSize];
    for (int i = 0; i < iOuterSize; i++) {
        for (int j = 0; j < list.get(i).size(); j++) {
            iArray[i][j] = list.get(i).get(j);
        }
    }
</code>```

Body:
private ArrayList<ArrayList<Integer>> list ;
 int size = list.size();

         int[][] iArray = new int[size][size];
for (int i=0; i<size; ++i){
             for (j = 0; j<size; ++j){
                 iArray[i][j] = list.get(j +( list.size() * i));
     }
}

I'm using the following code but it gives me error. please suggest.

Body:
What error are you getting?
the problem could be that your inner ArrayList is smaler then the outer one.
the other way around it wouldnt cause an error but your 2D Array would be incomplete.
and you have an syntax error in the inner for loop your j doenst have an variable type
you have to do something like this

    int iOuterSize = list.size();
    int iBiggestInnerSize = -1;
    for (ArrayList<Integer> arrayList : list) {
        int iCurInnerSize = arrayList.size();
        if (iCurInnerSize > iBiggestInnerSize) {
            iBiggestInnerSize = iCurInnerSize;
        }
    }
    int[][] iArray = new int[iOuterSize][iBiggestInnerSize];
    for (int i = 0; i < iOuterSize; i++) {
        for (int j = 0; j < list.get(i).size(); j++) {
            iArray[i][j] = list.get(i).get(j);
        }
    }


问:
Best ASP.NET reporting engine with custom reports creation ability
We need to choose the reporting engine for our ASP.NET application. The main functional requirement is an ability for end users (not programmers, just normal users) to create custom reports. We will be using SQL Server as a database so I am aware of some options: SQL Server Reporting services, Crystal Reports, Active Reports, even WindwardReports.

But frankly speaking I've never used any of those except Reporting services and it's quite difficult to choose which one suits the best to customer needs of custom reports creation. Is it possible to get some pros and cons for these options or at least your advice on what would be better to use in this case. Thanks a lot.

答:
First off, thank you for the up-front mention of Windward. It's nice to see we're on the default short list :)

It really depends on what report desing approach works best for you. If you prefer a programming type approach inside an IDE, then it's Crystal, SSRS, etc. If you prefer an approach where you can design the reports in Microsoft Word, Excel, or PowerPoint (which IMHO makes report design and editing fast & easy), then take a close look at Windward Reports. (Disclaimer, I'm the CTO at Windward.)

For general information, I suggest dotnet-reports and reporting-software. The key to a system that works well for you is one where the design tool is a natural fit for your style - so try several.

ContentLicense: CC BY-SA 2.5


问:
How to convert two's complement binary to decimal in MIPS
I'm reading in binary machine code from a file and translating it back into assembly instructions and am having problems with negative immediate values (last 16 bits of an I-Type instruction). I am reading the line in 1 bit at a time and converting the binary numbers into decimal numbers as I go on using this function:

```<code>readBits:   #Function to read bits
    add $t5, $a0, $zero     #set t5 to parameter
    li $t1, 2             #base value (2)
    li $t7 , 0            #j = 0
    li $s0, 0             # Set return value to 0
    li $s7, '0'           # load ascii value of '0'
    readBitsLoop:
        beq $t7, $t5, endReadBitsLoop   #If we are past our length's iteration, we have rs
        lb $t2, fileInputBuffer($t0)    #Load in byte in file
        addi $t0, $t0, 1       # iterator for file++
        addi $t7, $t7, 1       # j++
        mult $s0, $t1          #multiply return value and base
        mflo $t3              #set result to t5
        sub $t4, $t2, $s7   #subtract fileInputBuffer[i] and ascii value for '0'
        add $s0, $t3,$t4        #Add those 2 together

        j readBitsLoop      #Jump to start of loop
        endReadBitsLoop:
            add $v0, $s0, $zero #move return value to return register
            jr $ra  #go back to where we were
</code>```

This function takes in an input of how long that section should be. For example, for the immediate value, the parameter would be 16.

This works fine for positive values, but not for negative ones because I need to complement it before parsing. Is there an easy way to do this? Or is there some way to do that conversion after it's already in decimal?

Thanks for any help with this. Let me know if you need to see more code to understand what i'm trying to do.

答:
I think what you actually want is to sign-extend a 16-bit signed 2's complement integer to a 32-bit signed 2's complement integer that fills a register, so you can use it with add / sub / multiply instructions.

You only need to convert to decimal if you want to print it as a string (i.e. do what v0=1 syscall does yourself.)

Anyway, an arithmetic right shift is one way to make copies of the sign bit.  First left shift your narrow integer so its sign bit is at the left of the register, then use an arithmetic shift.

```<code>#  $s0 = all 4 bytes of a 32-bit I-type instruction
# where the immediate is the low 16 bits.
sll  $t3,  $s0, 16             # shift left logical
sra  $t3,  $t3, 16             # shift right arithmetic
# $t3 = a 32-bit integer from -65536 to +65535 = the immediate
# $t3 = sign_extend(low16($s0))
</code>```

MIPS instructions are always aligned, so you can safely lw the whole instruction or lh the low half, without needing to combine the two 8-bit halves of the immediate with two lb instructions and a shift/OR.

And BTW, you're reading one byte at a time, not one bit.  addi by 1 advances $t0 by a whole byte every loop iteration.

```<code>    lb $t2, fileInputBuffer($t0)    #Load in byte in file
    addi $t0, $t0, 1
</code>```

You appear to be using mult by a constant 2 instead of a left-shift.  This is highly inefficient.  Even better, you can left shift by adding a number to itself.  addu $t3, $s0, $s0 does $t3 = $s0 << 1 = $s0 * 2.

See the basic MIPS instruction set.

Body:
I'm reading in binary machine code from a file and translating it back into assembly instructions and am having problems with negative immediate values (last 16 bits of an I-Type instruction). I am reading the line in 1 bit at a time and converting the binary numbers into decimal numbers as I go on using this function:

readBits:   #Function to read bits
    add $t5, $a0, $zero     #set t5 to parameter
    li $t1, 2             #base value (2)
    li $t7 , 0            #j = 0
    li $s0, 0             # Set return value to 0
    li $s7, '0'           # load ascii value of '0'
    readBitsLoop:
        beq $t7, $t5, endReadBitsLoop   #If we are past our length's iteration, we have rs
        lb $t2, fileInputBuffer($t0)    #Load in byte in file
        addi $t0, $t0, 1       # iterator for file++
        addi $t7, $t7, 1       # j++
        mult $s0, $t1          #multiply return value and base
        mflo $t3              #set result to t5
        sub $t4, $t2, $s7   #subtract fileInputBuffer[i] and ascii value for '0'
        add $s0, $t3,$t4        #Add those 2 together

        j readBitsLoop      #Jump to start of loop
        endReadBitsLoop:
            add $v0, $s0, $zero #move return value to return register
            jr $ra  #go back to where we were

This function takes in an input of how long that section should be. For example, for the immediate value, the parameter would be 16.

This works fine for positive values, but not for negative ones because I need to complement it before parsing. Is there an easy way to do this? Or is there some way to do that conversion after it's already in decimal?

Thanks for any help with this. Let me know if you need to see more code to understand what i'm trying to do.

Body:
I think what you actually want is to sign-extend a 16-bit signed 2's complement integer to a 32-bit signed 2's complement integer that fills a register, so you can use it with add / sub / multiply instructions.

You only need to convert to decimal if you want to print it as a string (i.e. do what v0=1 syscall does yourself.)

Anyway, an arithmetic right shift is one way to make copies of the sign bit.  First left shift your narrow integer so its sign bit is at the left of the register, then use an arithmetic shift.

#  $s0 = all 4 bytes of a 32-bit I-type instruction
# where the immediate is the low 16 bits.
sll  $t3,  $s0, 16             # shift left logical
sra  $t3,  $t3, 16             # shift right arithmetic
# $t3 = a 32-bit integer from -65536 to +65535 = the immediate
# $t3 = sign_extend(low16($s0))

MIPS instructions are always aligned, so you can safely lw the whole instruction or lh the low half, without needing to combine the two 8-bit halves of the immediate with two lb instructions and a shift/OR.

And BTW, you're reading one byte at a time, not one bit.  addi by 1 advances $t0 by a whole byte every loop iteration.

    lb $t2, fileInputBuffer($t0)    #Load in byte in file
    addi $t0, $t0, 1

You appear to be using mult by a constant 2 instead of a left-shift.  This is highly inefficient.  Even better, you can left shift by adding a number to itself.  addu $t3, $s0, $s0 does $t3 = $s0 << 1 = $s0 * 2.

See the basic MIPS instruction set.


问:
Sorting an ArrayList by the second word in a string
I've currently got a .txt file i need to read and output data based on what is inside. I've currently got the file to open and saved each line in the file into an ArrayList.

The .txt file is setup like this ;

2380213012999 1508434343432 david dead

4327482397488 7439857934858 john alive

3857948998099 2222783749887 martin killed kelly

3857948998099 2222783749887 john killed david

Current code ;

```<code> {
    try {
        File file = new File("input.txt");
        FileReader fileReader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        StringBuffer stringBuffer = new StringBuffer();
        String line;
        ArrayList<String> txtline = new ArrayList<String>();
        while ((line = bufferedReader.readLine()) != null) {
            txtline.add(line);
            System.out.println(txtline);
        }

        fileReader.close();
        System.out.println(stringBuffer.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}
</code>```

I'm just wondering if there is a way to sort each line of text by the 2nd large number, I've looked and I just can't seem to find anything. A point in the right direction or some guidance would be amazing as I'm currently stumped as I need to do this before i progress any further.

答:
Put this after your while-loop

```<code>java.util.Collections.sort(txtLine, new Comparator<String>() {
    public void compare(String lineA, String lineB) {
        String wordA2 = lineA.split(" ")[1];
        String wordB2 = lineB.split(" ")[1];
        return wordA2.compareTo(wordB2);
    }
});
</code>```

Can be done more efficiently, but the code doesn't get much shorter than this (unless you use lambdas).

```<code>java.util.Collections.sort(txtLine, (String lineA, String lineB) -> {
        String wordA2 = lineA.split(" ")[1];
        String wordB2 = lineB.split(" ")[1];
        return wordA2.compareTo(wordB2);
});
</code>```

Body:
I've currently got a .txt file i need to read and output data based on what is inside. I've currently got the file to open and saved each line in the file into an ArrayList.

The .txt file is setup like this ;

2380213012999 1508434343432 david dead

4327482397488 7439857934858 john alive

3857948998099 2222783749887 martin killed kelly

3857948998099 2222783749887 john killed david

Current code ;

 {
    try {
        File file = new File("input.txt");
        FileReader fileReader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        StringBuffer stringBuffer = new StringBuffer();
        String line;
        ArrayList<String> txtline = new ArrayList<String>();
        while ((line = bufferedReader.readLine()) != null) {
            txtline.add(line);
            System.out.println(txtline);
        }

        fileReader.close();
        System.out.println(stringBuffer.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }
}

}

I'm just wondering if there is a way to sort each line of text by the 2nd large number, I've looked and I just can't seem to find anything. A point in the right direction or some guidance would be amazing as I'm currently stumped as I need to do this before i progress any further.

Body:
Put this after your while-loop

java.util.Collections.sort(txtLine, new Comparator<String>() {
    public void compare(String lineA, String lineB) {
        String wordA2 = lineA.split(" ")[1];
        String wordB2 = lineB.split(" ")[1];
        return wordA2.compareTo(wordB2);
    }
});

Can be done more efficiently, but the code doesn't get much shorter than this (unless you use lambdas).

java.util.Collections.sort(txtLine, (String lineA, String lineB) -> {
        String wordA2 = lineA.split(" ")[1];
        String wordB2 = lineB.split(" ")[1];
        return wordA2.compareTo(wordB2);
});


问:
Tensorflow: optimize over input with gradient descent
I have a TensorFlow model (a convolutional neural network) which I successfully trained using gradient descent (GD) on some input data.

Now, in a second step, I would like to provide an input image as initialization then and optimize over this input image with fixed network parameters using GD. The loss function will be a different one, but this a detail.

So, my main question is how to tell the gradient descent algorithm to

stop optimizing the network parameters

to optimize over the input image

The first can probably done with this
Holding variables constant during optimizer

Do you guys have ideas about the second point?

I guess I can recode the gradient descent algorithm myself using the TF gradient function, but my gut feeling tells me that there should be an easier way, which also allows me to benefit from more complex GD variants (Adam etc.).

答:
represent an image as tf.Variable with trainable=True

initialise this variable with the starting image (initial guess)

recreate the NN graph using TF variables with trainable=False and copy the weights from the trained NN graph using tf.assign

calculate the loss function

plug the loss into any TF optimiser algorithm you want


问:
How to convert dates from several formats into one single format?
I have several different formats of dates in one field.  It looks like this.

```<code>20200228

12/15/2021

7/6/2020

Oct 29 2017 12:00AM

Oct 31 20

08/01/18
</code>```

How can I get everything standardized as MM/DD/YYYY?

```<code>20200228 --> 02/28/2020

12/15/2021 --> no change

Oct 31 2017 12:00AM --> 10/31/2017

Oct 31 20 --> 10/31/2017

08/01/18 --> 08/01/2018
</code>```

I tried all kinds of Cast and Convert combinations, but I couldn't get anything to work.  Does anyone out there have a solution for this?  It doesn't have to be one pass in one query.  I'm sure it can be done in several iterations, but I don't know how to tackle it.

答:
Personally, I'd create a persisted computed column using a CASE statement with IsDate (available since 2008):

```<code>ALTER TABLE dbo.YourTable
ADD YourDate_DateTime AS CASE WHEN ISDATE(YourDate) = 1 THEN CAST(YourDate AS DATETIME) ELSE NULL END PERSISTED
GO
</code>```

That way you don't need to constantly perform the calculation every time. Anything that SQL doesn't recognize as being a date will be NULL, but there's really no way around that short of fixing every such value. At least this way you can easily search for NULL values to go fix.

Body:
I have several different formats of dates in one field.  It looks like this.

20200228

12/15/2021

7/6/2020

Oct 29 2017 12:00AM

Oct 31 20

08/01/18

How can I get everything standardized as MM/DD/YYYY?

20200228 --> 02/28/2020

12/15/2021 --> no change

Oct 31 2017 12:00AM --> 10/31/2017

Oct 31 20 --> 10/31/2017

08/01/18 --> 08/01/2018

I tried all kinds of Cast and Convert combinations, but I couldn't get anything to work.  Does anyone out there have a solution for this?  It doesn't have to be one pass in one query.  I'm sure it can be done in several iterations, but I don't know how to tackle it.

Body:
Personally, I'd create a persisted computed column using a CASE statement with IsDate (available since 2008):

ALTER TABLE dbo.YourTable
ADD YourDate_DateTime AS CASE WHEN ISDATE(YourDate) = 1 THEN CAST(YourDate AS DATETIME) ELSE NULL END PERSISTED
GO

That way you don't need to constantly perform the calculation every time. Anything that SQL doesn't recognize as being a date will be NULL, but there's really no way around that short of fixing every such value. At least this way you can easily search for NULL values to go fix.


问:
Dynamically Displaying Text with TextView (Android)
Basically what I want to do in my Android app is use TextView to display two different pieces of text at once. So in code, I want to be able to do something like this:

```<code>    LinearLayout ll = new LinearLayout(this);
    TextView text = new TextView(this);
    text.setTextColor(0xFF000000);
    text.setGravity(Gravity.CENTER_HORIZONTAL);
    text.setTextSize(20f);
    text.setText("Text1");
    text.setTextSize(14f);
    text.setColor(0xFF0000FF);
    text.setText("\nText2");
    ll.addView(text);
</code>```

To clarify, I am trying to display a black "Text1" and a blue "Text2" at once using only a single TextView. Obviously this doesn't work out using the code above. I've considered using a second TextView but that seems like a waste of effort and memory to me. I'm sure the brilliant minds here can come up with the best solution to this.

Thank you very much in advance for your time and your assistance.

答:
Once a View is added to a ViewGroup of which LinearLayout is a descendant you do not need to readd it to update its display. If you preform any changes on a view that requires it to change its display it will handle all the proper notifications about required redraws or relayouts by calling View#invalidate and View#requestLayout where appropriate.

In addition, because all UI changes are handled on the same thread you do not need to worry about calling multiple methods that will update the UI. This is because of two reasons, first, the execution of the redraws will not occur until your code is finished, second, android has optimizations built in that combines multiple invalidate calls into one.

So, the only thing you need to worry about is getting a proper reference to your TextView instance and then you can call all the methods on it that you need to make it display what you wish.

Since you are creating your Views manually and not from xml you need to add your root ViewGroup to the Activity by calling Activity#setContentView.

Edit:

Then you're going to need to learn about SpannableString and SpannableStringBuilder. There is some very brief documentation here: Selecting, Highlighting, or Styling Portions of Text

Body:
Basically what I want to do in my Android app is use TextView to display two different pieces of text at once. So in code, I want to be able to do something like this:

    LinearLayout ll = new LinearLayout(this);
    TextView text = new TextView(this);
    text.setTextColor(0xFF000000);
    text.setGravity(Gravity.CENTER_HORIZONTAL);
    text.setTextSize(20f);
    text.setText("Text1");
    text.setTextSize(14f);
    text.setColor(0xFF0000FF);
    text.setText("\nText2");
    ll.addView(text);

To clarify, I am trying to display a black "Text1" and a blue "Text2" at once using only a single TextView. Obviously this doesn't work out using the code above. I've considered using a second TextView but that seems like a waste of effort and memory to me. I'm sure the brilliant minds here can come up with the best solution to this.

Thank you very much in advance for your time and your assistance.


问:
Is there a way to make a child process output stream flush its data more frequently?
I am trying to pipe a child process' standard output to the parent's standard output:

```<code>import {exec} from 'child_process';

console.log(new Date() + " starting")
const child = exec(/* some command */);
child.stdout.pipe(process.stdout);
</code>```

This works, but the child process generates data quite slowly relative to the size of the pipe's buffer. The data comes in large chunks and not frequently.

For example, if I watch the child output stream like this:

```<code>child.stdout.on('data', data => console.log(new Date(), data.length));
</code>```

The output is

```<code>2017-11-15T21:53:44.128Z starting
2017-11-15T21:53:58.319Z 8192
2017-11-15T21:54:02.321Z 8192
2017-11-15T21:54:07.384Z 8192
2017-11-15T21:54:11.333Z 8192
2017-11-15T21:54:15.281Z 8192
2017-11-15T21:54:19.008Z 3967
</code>```

Is there a way to have the child output stream use a smaller buffer or flush more frequently?

答:
The OS and child process are in control of output buffering.

As an example, Python has a -u option that causes writes to be flushed (also the PYTHONUNBUFFERED env var). The following example adapted from the question shows the difference in behaviour of a command that writes an integer to screen every second when using unbuffered and normal output.

```<code>const {exec} = require('child_process')

function run(cmd){
  return new Promise((resolve, reject) => {
    console.log("%s starting %s", Date.now(), cmd)
    const child = exec(cmd)
    child.stdout.pipe(process.stdout)
    child.stderr.pipe(process.stderr)
    child.on('exit', exit => {
      console.log('%s exit', Date.now(), exit)
      if ( exit === 0 ) return resolve(exit)
      reject(new Error(exit))
    })
  })
}

async function go(){
  await run('python -uc "import time; [print(i,str(time.sleep(1))) for i in range(10)]"')
  await run('python -c "import time; [print(i,str(time.sleep(1))) for i in range(10)]"')
}

go()
</code>```

If the child process being run doesn't have an equivalent option or config to flush output then this Unix + Linux question includes a number of tricks to disable buffered output by modifying how the child process is run, by either allocating a pseudo terminal or modifying it's buffers directly.

There's also node-pty and node-pty2 which will spawn processes with a pseudo terminal which would be similar to what expects unbuffer command does. I've not used either module before though so can't vouch for them.

Body:
I am trying to pipe a child process' standard output to the parent's standard output:

import {exec} from 'child_process';

console.log(new Date() + " starting")
const child = exec(/* some command */);
child.stdout.pipe(process.stdout);

This works, but the child process generates data quite slowly relative to the size of the pipe's buffer. The data comes in large chunks and not frequently.

For example, if I watch the child output stream like this:

child.stdout.on('data', data => console.log(new Date(), data.length));

The output is

2017-11-15T21:53:44.128Z starting
2017-11-15T21:53:58.319Z 8192
2017-11-15T21:54:02.321Z 8192
2017-11-15T21:54:07.384Z 8192
2017-11-15T21:54:11.333Z 8192
2017-11-15T21:54:15.281Z 8192
2017-11-15T21:54:19.008Z 3967

Is there a way to have the child output stream use a smaller buffer or flush more frequently?

Body:
The OS and child process are in control of output buffering.

As an example, Python has a -u option that causes writes to be flushed (also the PYTHONUNBUFFERED env var). The following example adapted from the question shows the difference in behaviour of a command that writes an integer to screen every second when using unbuffered and normal output.

const {exec} = require('child_process')

function run(cmd){
  return new Promise((resolve, reject) => {
    console.log("%s starting %s", Date.now(), cmd)
    const child = exec(cmd)
    child.stdout.pipe(process.stdout)
    child.stderr.pipe(process.stderr)
    child.on('exit', exit => {
      console.log('%s exit', Date.now(), exit)
      if ( exit === 0 ) return resolve(exit)
      reject(new Error(exit))
    })
  })
}

async function go(){
  await run('python -uc "import time; [print(i,str(time.sleep(1))) for i in range(10)]"')
  await run('python -c "import time; [print(i,str(time.sleep(1))) for i in range(10)]"')
}

go()

If the child process being run doesn't have an equivalent option or config to flush output then this Unix + Linux question includes a number of tricks to disable buffered output by modifying how the child process is run, by either allocating a pseudo terminal or modifying it's buffers directly.

There's also node-pty and node-pty2 which will spawn processes with a pseudo terminal which would be similar to what expects unbuffer command does. I've not used either module before though so can't vouch for them.


问:
Subclass Polymer element filling base class insertion points
I have a set of Polymer components which are subclasses of another component. I want to populate the template of the superclass based on the template of the subclass. (See here for someone else looking for a solution to a similar problem, unfortunately with no solution.) The usage looks something like this:

<media-tabs tabs-title="Alternative input">
  <template>
    <media-blackout></media-blackout>
    <media-slates></media-slates>
    <media-playlists></media-playlists>
    <media-queue></media-queue>
  </template>
</media-tabs>
```

<pre class="lang-html prettyprint-override"><code><!-- media-tabs.html -->
<paper-card heading="[[tabsTitle]]" class="fill-h fill-v">
  <div class="card-content">
    <paper-tabs id="tabs" selected="{{selectedIndex}}" selectable>
    </paper-tabs>
    <iron-pages id="content" selected="{{selectedIndex}}">
    </iron-pages>
  </div>
</paper-card>
</code>```

// media-tabs.js
ready() {
  super.ready();
  this.selectedIndex = 0;
  const template = this.querySelector('template');
  const instance = this._stampTemplate(template);
  const tabs = Array.from(instance.children);
  tabs.forEach((elm) => {
    const content = elm.constructor.template.content;
    this.$.tabs.appendChild(content.querySelector('#title'));
    this.$.content.appendChild(content.querySelector('#content'));
  });
}
```

<pre class="lang-html prettyprint-override"><code><!-- media-tab.html -->
<paper-tab id="title"></paper-tab>
<div id="content"></div>
</code>```

Blackout

Lorem ipsum dolor sit amet

```

<pre class="lang-js prettyprint-override"><code>// media-blackout.js -- is a subclass of media-tab
static get template() {
  if (!superTemplate) {
    const thisTemplate = Polymer.DomModule.import(this.is, 'template');
    superTemplate = MediaTab.template.cloneNode(true);
    const title = thisTemplate.content.querySelector('#title').textContent;
    const content = thisTemplate.content.querySelector('#content');
    const children = Array.from(content.children);

    superTemplate.content.querySelector('#title').innerHTML = title;
    children.forEach((child) => {
      superTemplate.content.querySelector('#content').appendChild(child);
    });
  }
  return superTemplate;
}
// repeat above for media-playlists, media-queue, and media-slates
</code>```

This setup works. However, the template() getter is identical in the media-tab subclasses, and I want to find a way to move that logic into the superclass, without the code in the superclass needing to know about the subclass implementation details.

I have attempted to create getters for the two fields the superclass would need to pull from (eg, const title = this.templateTitleElement.textContent;), however my implementations either poke the element's template property in some way (resulting a stack overflow), or else try to access elements before they're available (eg, return this.$.title;).

答:
My previous solution had issues with bubbling events from within the tab content, so I was forced to come up with another solution:

<media-tabs tabs-title="Alternative input" on-play-slate="handlePlayTapped">
  <media-blackout></media-blackout>
  <media-slates></media-slates>
  <media-playlists></media-playlists>
  <media-queue></media-queue>
</media-tabs>
```

<p>You can see I've removed the template from the <code>media-tabs</code> declaration.</p>

<pre class="lang-html prettyprint-override"><code><!-- media-tabs.html -->
<paper-card heading="[[tabsTitle]]">
  <div class="card-content">
    <paper-tabs id="tabs" selected="{{selectedIndex}}" selectable></paper-tabs>
    <iron-pages id="content" selected="[[selectedIndex]]">
      <slot></slot>
    </iron-pages>
  </div>
</paper-card>
</code>```

You can see that I've added the <slot> insertion point to the iron-pages.

// media-tabs.js
ready() {
  super.ready();
  const children = Array.from(this.children);
  children.forEach((child) => {
    const template = Object.getPrototypeOf(child.constructor).template;
    const instance = this._stampTemplate(template);
    instance.$.title.innerHTML = child.tabTitle;
    this.$.tabs.appendChild(instance.$.title);
  });
}
```

<p>Now I only append children to the <code>paper-tabs</code> element, rather than both <code>paper-tabs</code> and <code>iron-pages</code>. <code>Object.getPrototypeOf(child.constructor)</code> returns the constructor of <code>child</code>'s superclass; this means I'm not simply assuming the child's superclass is MediaTab, although this can be improved as I <em>am</em> assuming the child's superclass has an element with <code>id="title"</code> and a property <code>tabTitle</code>.</p>

<pre class="lang-html prettyprint-override"><code><!-- media-tab.html -->
<paper-tab id="title"></paper-tab>
</code>```

// media-tab.js
static get properties() {
  return {
    tabTitle: String,
  };
}
```

<p>The <code>media-tab</code> template doesn't contain a content div any more, and the superclass defines the <code>tabTitle</code> property referenced in <code>media-tabs.js</code>.</p>

<pre class="lang-html prettyprint-override"><code><!-- media-blackout.html -->
<p>Lorem ipsum dolor sit amet</p>
<!-- repeat above for media-playlists, media-queue, and media-slates -->
</code>```

The media-tab subclasses no longer store their tab title in HTML, they only have content.

// media-blackout.js
class MediaBlackout extends MediaTab {
  // ...

  static get properties() {
    return {
      tabTitle: {
        type: String,
        value: 'Blackout',
        readOnly: true,
      },
    };
  }
}
// repeat above for media-playlists, media-queue, and media-slates
```

Instead of having the subclass's title in a span, it's defined as a property of the class.

This solution doesn't use a mixin, and events being fired from within the MediaTab elements can bubble up to the top of the app.

Body:
I have a set of Polymer components which are subclasses of another component. I want to populate the template of the superclass based on the template of the subclass. (See here for someone else looking for a solution to a similar problem, unfortunately with no solution.) The usage looks something like this:

<media-tabs tabs-title="Alternative input">
  <template>
    <media-blackout></media-blackout>
    <media-slates></media-slates>
    <media-playlists></media-playlists>
    <media-queue></media-queue>
  </template>
</media-tabs>

<paper-card heading="[[tabsTitle]]" class="fill-h fill-v">

    <paper-tabs id="tabs" selected="{{selectedIndex}}" selectable>
    </paper-tabs>
    <iron-pages id="content" selected="{{selectedIndex}}">
    </iron-pages>

</paper-card>

// media-tabs.js
ready() {
  super.ready();
  this.selectedIndex = 0;
  const template = this.querySelector('template');
  const instance = this._stampTemplate(template);
  const tabs = Array.from(instance.children);
  tabs.forEach((elm) => {
    const content = elm.constructor.template.content;
    this.$.tabs.appendChild(content.querySelector('#title'));
    this.$.content.appendChild(content.querySelector('#content'));
  });
}

<paper-tab id="title"></paper-tab>

Blackout

Lorem ipsum dolor sit amet

// media-blackout.js -- is a subclass of media-tab
static get template() {
  if (!superTemplate) {
    const thisTemplate = Polymer.DomModule.import(this.is, 'template');
    superTemplate = MediaTab.template.cloneNode(true);
    const title = thisTemplate.content.querySelector('#title').textContent;
    const content = thisTemplate.content.querySelector('#content');
    const children = Array.from(content.children);

    superTemplate.content.querySelector('#title').innerHTML = title;
    children.forEach((child) => {
      superTemplate.content.querySelector('#content').appendChild(child);
    });
  }
  return superTemplate;
}
// repeat above for media-playlists, media-queue, and media-slates

This setup works. However, the template() getter is identical in the media-tab subclasses, and I want to find a way to move that logic into the superclass, without the code in the superclass needing to know about the subclass implementation details.

I have attempted to create getters for the two fields the superclass would need to pull from (eg, const title = this.templateTitleElement.textContent;), however my implementations either poke the element's template property in some way (resulting a stack overflow), or else try to access elements before they're available (eg, return this.$.title;).

Body:
My previous solution had issues with bubbling events from within the tab content, so I was forced to come up with another solution:

<!-- control.html -->
<media-tabs tabs-title="Alternative input" on-play-slate="handlePlayTapped">
  <media-blackout></media-blackout>
  <media-slates></media-slates>
  <media-playlists></media-playlists>
  <media-queue></media-queue>
</media-tabs>

You can see I've removed the template from the media-tabs declaration.

<!-- media-tabs.html -->
<paper-card heading="[[tabsTitle]]">
  <div class="card-content">
    <paper-tabs id="tabs" selected="{{selectedIndex}}" selectable></paper-tabs>
    <iron-pages id="content" selected="[[selectedIndex]]">
      <slot></slot>
    </iron-pages>
  </div>
</paper-card>

You can see that I've added the <slot> insertion point to the iron-pages.

// media-tabs.js
ready() {
  super.ready();
  const children = Array.from(this.children);
  children.forEach((child) => {
    const template = Object.getPrototypeOf(child.constructor).template;
    const instance = this._stampTemplate(template);
    instance.$.title.innerHTML = child.tabTitle;
    this.$.tabs.appendChild(instance.$.title);
  });
}

Now I only append children to the paper-tabs element, rather than both paper-tabs and iron-pages. Object.getPrototypeOf(child.constructor) returns the constructor of child's superclass; this means I'm not simply assuming the child's superclass is MediaTab, although this can be improved as I am assuming the child's superclass has an element with id="title" and a property tabTitle.

<!-- media-tab.html -->
<paper-tab id="title"></paper-tab>

// media-tab.js
static get properties() {
  return {
    tabTitle: String,
  };
}

The media-tab template doesn't contain a content div any more, and the superclass defines the tabTitle property referenced in media-tabs.js.

<!-- media-blackout.html -->
<p>Lorem ipsum dolor sit amet</p>
<!-- repeat above for media-playlists, media-queue, and media-slates -->

The media-tab subclasses no longer store their tab title in HTML, they only have content.

// media-blackout.js
class MediaBlackout extends MediaTab {
  // ...

  static get properties() {
    return {
      tabTitle: {
        type: String,
        value: 'Blackout',
        readOnly: true,
      },
    };
  }
}
// repeat above for media-playlists, media-queue, and media-slates

Instead of having the subclass's title in a span, it's defined as a property of the class.

This solution doesn't use a mixin, and events being fired from within the MediaTab elements can bubble up to the top of the app.


问:
Does Facebook SDK 3.23.1 include the FBNotifications library?
I am following the Push Campaigns Quickstart at https://developers.facebook.com/docs/push-notifications/quickstart. At the beginning of the document, I found this paragraph:

Prior to sending in-app notifications you will also need to integrate
  the FBNotifications library.

Based on the documentation at https://github.com/facebook/FBNotifications, I need to add the following to my gradle dependencies:

```<code>compile 'com.facebook.android:notifications:1.+'
</code>```

I already have this in my gradle dependencies:

```<code>compile 'com.facebook.android:facebook-android-sdk:3.23.1'
</code>```

Does Facebook SDK 3.23.1 (com.facebook.android:facebook-android-sdk:3.23.1) include the FBNotifications library (com.facebook.android:notifications:1.+)? Thank you.

EDIT: In the question at Android In-App Notifications Integration Popup not showing, the asker is using both 'com.facebook.android:facebook-android-sdk:4.+' and 'com.facebook.android:notifications:1.+'. That makes me think that Facebook SDK does not include the FBNotifications library.

答:
I was examining the code at https://github.com/facebook/FBNotifications/blob/master/Android/notifications-example/build.gradle and I found this block of code:

```<code>dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.google.android.gms:play-services:8.4.0'
    compile 'com.facebook.android:facebook-android-sdk:4.+'
    compile 'commons-io:commons-io:2.4'
    compile project(':notifications')
    apply plugin: 'com.google.gms.google-services'
}
</code>```

I see how the code includes both 'com.facebook.android:facebook-android-sdk:4.+' and project(':notifications'). Conclusion: Facebook SDK does not include FBNotifications.

Body:
I am following the Push Campaigns Quickstart at https://developers.facebook.com/docs/push-notifications/quickstart. At the beginning of the document, I found this paragraph:

Prior to sending in-app notifications you will also need to integrate
  the FBNotifications library.

Based on the documentation at https://github.com/facebook/FBNotifications, I need to add the following to my gradle dependencies:

compile 'com.facebook.android:notifications:1.+'

I already have this in my gradle dependencies:

compile 'com.facebook.android:facebook-android-sdk:3.23.1'

Does Facebook SDK 3.23.1 (com.facebook.android:facebook-android-sdk:3.23.1) include the FBNotifications library (com.facebook.android:notifications:1.+)? Thank you.

EDIT: In the question at Android In-App Notifications Integration Popup not showing, the asker is using both 'com.facebook.android:facebook-android-sdk:4.+' and 'com.facebook.android:notifications:1.+'. That makes me think that Facebook SDK does not include the FBNotifications library.

Body:
I was examining the code at https://github.com/facebook/FBNotifications/blob/master/Android/notifications-example/build.gradle and I found this block of code:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:23.1.1'
    compile 'com.android.support:design:23.1.1'
    compile 'com.google.android.gms:play-services:8.4.0'
    compile 'com.facebook.android:facebook-android-sdk:4.+'
    compile 'commons-io:commons-io:2.4'
    compile project(':notifications')
    apply plugin: 'com.google.gms.google-services'
}

I see how the code includes both 'com.facebook.android:facebook-android-sdk:4.+' and project(':notifications'). Conclusion: Facebook SDK does not include FBNotifications.


问:
Searching annotation in mapkit
im trying to add a search bar to the current mapkit im doing.

The search bar will be able to search for the different location name (annotations on the map) in a table view.

When users click on a certain cell it will direct them to the specific annotation on the map.

Any ideas on how to do it? I googled for answers, but most of the tutorial teach us on searching through sqlite and so on.

答:
@funatsg i suggest u to take the data from a a particular index from you UITableView search result and take that data to your mapView and then start searching for that paticular location in a map (eg:-by giving that string to google map) and you will get the particular location.
I would like to suggest a link to you which is some how similar to your condition.....see how the map is searching the data of the text from UITextField..try this link

Hope it will help u and solve your problem!!!

Title: Searching annotation in mapkit


问:
Why is the waitUntil method protected for ElementsCollection?
As you can see in the documentation, the waitUntil method is protected for ElementsCollection:

http://selenide.org/javadoc/3.7/com/codeborne/selenide/ElementsCollection.html

This is not the case for SelenideElement for example:

http://selenide.org/javadoc/3.7/com/codeborne/selenide/SelenideElement.html

Why is the method protected for ElementsCollection?

答:
I think the idea behind this is that it make sense to apply waitUntil + visible/disappear/hasText/etc. Condition combination for single element, but totally useless to collection of elements and potentially buggy.

There is no way to set how many elements should disappear or should appear while you are waiting, taking in account performance cost it may bring - that was the right decision.


问:
knitr package loading error stringr
I get the following error:

1Error in library(stringr) :
  Package 'stringr' version 1.2.0 cannot be unloaded

when loading the following packages in my knitr document:

library(checkpoint)
checkpoint("2017-01-01")
library(stringr)
library(plyr)
library(tidyr)
library(dplyr)
library(knitr)
library(readr)
library(readxl)
library(ggplot2)
library(scales)
library(ggthemes)
library(lubridate)
library(xtable)
library(zoo)
library(gridExtra)

when I remove stringr then I get the error:

Error in mutate_impl(.data, dots) : could not find function "str_sub"

...any ideas? I am using Mac OSX Mavericks. I copied the files over from a Windows 7 (where it worked) and I'm assuming that has something to do with it.

Thank you in advance!

答:
There is a conflict due to the stringr package being newer (2017-02-18) than your checkpoint date of 2017-01-01.

You could clear the conflict by moving the date you use to something later, i.e.

```<code>checkpoint("2017-02-18") # or later
</code>```

Alternatively, if you find you have mixed dependencies that rely on packages that were not all current on the same date, I would recommend having a look at packrat (link), which is designed for that purpose.

Title: knitr package loading error stringr

Body:
There is a conflict due to the stringr package being newer (2017-02-18) than your checkpoint date of 2017-01-01.

You could clear the conflict by moving the date you use to something later, i.e.

checkpoint("2017-02-18") # or later

Alternatively, if you find you have mixed dependencies that rely on packages that were not all current on the same date, I would recommend having a look at packrat (link), which is designed for that purpose.


问:
How to config Webpack and Babel to use ES5 and ES6 in one project
How do I configure Babel and Webpack to load ES6 source code and ES5 vendor library, e.g.: jQuery, and our old lib javascript files in one project? They all have the same *.js extension.

```<code>  {
    test: /\.js$/,
    loader: 'babel',
    include: projectRoot,
    exclude: /node_modules/
  },
</code>```

Above loader will load ES6 correctly, but treat all js file as ES6. What about my old lib js files that are in ES5?

Here are my .babelrc file:

```<code>{
  "presets": ["es2015", "stage-2"],
  "plugins": ["transform-runtime"],
  "comments": false
}
</code>```

答: ES6 is backwards compatible with ES5. You shouldn't need to worry about this. ES5 code will not be transpiled and presumably will be copied verbatim (perhaps with some optimisation though I am not sure)</p>

Body:
How do I configure Babel and Webpack to load ES6 source code and ES5 vendor library, e.g.: jQuery, and our old lib javascript files in one project? They all have the same *.js extension.

  {
    test: /\.js$/,
    loader: 'babel',
    include: projectRoot,
    exclude: /node_modules/
  },

Above loader will load ES6 correctly, but treat all js file as ES6. What about my old lib js files that are in ES5?

Here are my .babelrc file:

{
  "presets": ["es2015", "stage-2"],
  "plugins": ["transform-runtime"],
  "comments": false
}


问:
Node.js serving over https
I'm testing Node.js application over https connection where I created certificates for localhost,

Certificate creation,

```<code>$ openssl genrsa -out localhost.key 2048
$ openssl req -new -x509 -key localhost.key -out localhost.cert -days 3650 -subj /CN=localhost
</code>```

Use this in server,

```<code>var options = {
  key: fs.readFileSync('./localhost.key'),
  cert: fs.readFileSync('./localhost.cert'),
};
var http2 = require('http2');
var app = express();
const server = http2.createSecureServer( options, app);
server.listen({ host: app_host, port: port});
</code>```

Start the node.js server as,

```<code>$ node server.js

Tested using simple curl command as,
$ curl -k https://localhost:9000/getcpuinfo
 {"hw": ...}
</code>```

"-k" option is to ignote certificate validation step.

But if I try to use pythons 'requests' module as shown below the request fails,
    $ python
    import requests

requests.get("https://localhost:9000/getcpuinfo")
            requests.exceptions.SSLError: ("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",)

So I used 'verify' option to make the request, it still fails.

requests.get("https://localhost:9000/getcpuinfo", verify=False)
          requests.exceptions.SSLError: ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)

What am I doing wrong? How do I workaround this issue using 'requests' module'? Shouldn't 'verify' prevent the check?

答:
It seems that there is a utility as part of nghttp2 called 'h2load' which works out of box for both protocols (http/1 and http/2). Thanks for all the answers/hints.

https://nghttp2.org/documentation/h2load-howto.html#basic-usage

Title: Node.js serving over https

Body:
I'm testing Node.js application over https connection where I created certificates for localhost,

Certificate creation,

$ openssl genrsa -out localhost.key 2048
$ openssl req -new -x509 -key localhost.key -out localhost.cert -days 3650 -subj /CN=localhost

Use this in server,

var options = {
  key: fs.readFileSync('./localhost.key'),
  cert: fs.readFileSync('./localhost.cert'),
};
var http2 = require('http2');
var app = express();
const server = http2.createSecureServer( options, app);
server.listen({ host: app_host, port: port});

Start the node.js server as,

$ node server.js

Tested using simple curl command as,
$ curl -k https://localhost:9000/getcpuinfo
 {"hw": ...}

"-k" option is to ignote certificate validation step.

But if I try to use pythons 'requests' module as shown below the request fails,
    $ python
    import requests

requests.get("https://localhost:9000/getcpuinfo")
            requests.exceptions.SSLError: ("bad handshake: Error([('SSL routines', 'tls_process_server_certificate', 'certificate verify failed')],)",)

So I used 'verify' option to make the request, it still fails.

requests.get("https://localhost:9000/getcpuinfo", verify=False)
          requests.exceptions.SSLError: ("bad handshake: SysCallError(-1, 'Unexpected EOF')",)

What am I doing wrong? How do I workaround this issue using 'requests' module'? Shouldn't 'verify' prevent the check?


问:
question number reordering
I have a list of question in my javascript file. Each question has a question number and question description and options. A question can be added anywhere in the list of questions. So if a question is added into the top of all questions, then i need to change the question numbers of all the below ones. How can achieve this. Can i use javascript for this?</p>

答:
This works.

```<code>var questions = ["A foo walks into a bar. What happens?", "Why did foo cross the road?"];

addQuestion("foo", 1);
function addQuestion(question, position)
{
    if(position > 0 && position < questions.length)
    {
        var firstHalf = questions.slice(0, position);
        var secondHalf = questions.slice(position, questions.length);
        firstHalf.push(question);
        questions = firstHalf.concat(secondHalf);
        console.log("slice");
    }else if(position <= 0)
    {
        questions.unshift(question);
        console.log("beginning");
    }else if(position >= questions.length)
    {
        questions.push(question);
        console.log("end");
    }
    updateQuestionList();
}

function updateQuestionList()
{
    var questions_list = document.getElementById("questions_list");
    questions_list.innerHTML = "";
    for(var i=0;i<questions.length;i++)
    {
        var question = document.createElement("LI");
        question.innerHTML = questions[i];
        questions_list.appendChild(question);
    }
}
</code>```

http://jsfiddle.net/jPxwW/1/

Title: question number reordering

Body:
This works.

<ol id="questions_list"></ol>

var questions = ["A foo walks into a bar. What happens?", "Why did foo cross the road?"];

addQuestion("foo", 1);
function addQuestion(question, position)
{
    if(position > 0 && position < questions.length)
    {
        var firstHalf = questions.slice(0, position);
        var secondHalf = questions.slice(position, questions.length);
        firstHalf.push(question);
        questions = firstHalf.concat(secondHalf);
        console.log("slice");
    }else if(position <= 0)
    {
        questions.unshift(question);
        console.log("beginning");
    }else if(position >= questions.length)
    {
        questions.push(question);
        console.log("end");
    }
    updateQuestionList();
}

function updateQuestionList()
{
    var questions_list = document.getElementById("questions_list");
    questions_list.innerHTML = "";
    for(var i=0;i<questions.length;i++)
    {
        var question = document.createElement("LI");
        question.innerHTML = questions[i];
        questions_list.appendChild(question);
    }
}

http://jsfiddle.net/jPxwW/1/


问:
How to force Github Pages to look at /build?
I'm using create-react-app which is serving its files from the /build folder. Typically Github Pages looks at index.html at the root level, but I'd like to direct it to look at /build for deployment.

I've tried to add "homepage": "/build" inside my package.json configuration, and Github Settings says it's deployed via <username>.github.io. However, the site just shows my README.md file.

Any help is appreciated :)

答:
The problem here is that this is a Web Browser issue, and not a Host issue. When you visit a webpage your browser always looks for the index.html file at the URL so localhost:8080 becomes localhost:8080/index.html.

This means that there are a couple ways to fix this. You could create an index.html file in your root directory and then have that serve up the scripts in the build folder like

You could also go through the pain and suffering of manually adding /build to the end of the URL. But you don't want users to have to do that, so you could write a script to redirect you there.

Good luck!

Body:
The problem here is that this is a Web Browser issue, and not a Host issue. When you visit a webpage your browser always looks for the index.html file at the URL so localhost:8080 becomes localhost:8080/index.html.

This means that there are a couple ways to fix this. You could create an index.html file in your root directory and then have that serve up the scripts in the build folder like <script src="build/main.js"></script>

You could also go through the pain and suffering of manually adding /build to the end of the URL. But you don't want users to have to do that, so you could write a script to redirect you there.

Good luck!


问:
Cannot read property 'create' of undefined -- react-dates error
While adding SingleDatePicker from 'react-dates' library, I got this error. Tried everything but couldn't find the error. The code is just to display the calender and display the selected date from the user. Please help!
Here is the code:

```<code>import React from 'react';
import moment from 'moment';
import { SingleDatePicker } from 'react-dates';
import 'react-dates/lib/css/_datepicker.css';

export default class ExpenseForm extends React.Component {
  state = {
    createdAt: moment(),
    calenderFocused: false
  };
  onDateChange = (createdAt) => {
    this.setState(() => ({ createdAt }));
  };

  onFocusChange = ({ focused }) => {
    this.setState(() => ({ calenderFocused: focused }));
  };

  render() {
    return (
      <div>
        <form>
          <SingleDatePicker
            date={this.state.createdAt}
            onDateChange={this.onDateChange}
            focused={this.state.calendcalenderFocused}
            onFocusChange={this.onFocusChange}
          />
        </form>
      </div>
    );
  }
};
</code>```

The error I am getting in the chrome-dev-tool:

```<code>Uncaught TypeError: Cannot read property 'create' of undefined
    at Object.createLTR [as create] (ThemedStyleSheet.js?17e6:46)
    at WithStyles.maybeCreateStyles (withStyles.js?55c9:121)
    at WithStyles.componentWillMount (withStyles.js?55c9:107)
    at callComponentWillMount (react-dom.development.js?cada:6337)
    at mountClassInstance (react-dom.development.js?cada:6393)
    at updateClassComponent (react-dom.development.js?cada:7849)
    at beginWork (react-dom.development.js?cada:8233)
    at performUnitOfWork (react-dom.development.js?cada:10215)
    at workLoop (react-dom.development.js?cada:10279)
    at HTMLUnknownElement.callCallback (react-dom.development.js?cada:540)
The above error occurred in the <withStyles(SingleDatePicker)> component:
    in withStyles(SingleDatePicker) (created by ExpenseForm)
    in form (created by ExpenseForm)
    in div (created by ExpenseForm)
    in ExpenseForm (created by AddExpensePage)
    in div (created by AddExpensePage)
    in AddExpensePage (created by Route)
    in Route (created by AppRouter)
    in Switch (created by AppRouter)
    in div (created by AppRouter)
    in Router (created by BrowserRouter)
    in BrowserRouter (created by AppRouter)
    in AppRouter
    in Provider
</code>```

答:
I got the same error in my tests and adding import 'react-dates/initialize'; fixed it.

Refer to https://github.com/airbnb/react-dates#initialize

Body:
While adding SingleDatePicker from 'react-dates' library, I got this error. Tried everything but couldn't find the error. The code is just to display the calender and display the selected date from the user. Please help!
Here is the code:

import React from 'react';
import moment from 'moment';
import { SingleDatePicker } from 'react-dates';
import 'react-dates/lib/css/_datepicker.css';

export default class ExpenseForm extends React.Component {
  state = {
    createdAt: moment(),
    calenderFocused: false
  };
  onDateChange = (createdAt) => {
    this.setState(() => ({ createdAt }));
  };

  onFocusChange = ({ focused }) => {
    this.setState(() => ({ calenderFocused: focused }));
  };

  render() {
    return (

        <form>
          <SingleDatePicker
            date={this.state.createdAt}
            onDateChange={this.onDateChange}
            focused={this.state.calendcalenderFocused}
            onFocusChange={this.onFocusChange}
          />
        </form>

    );
  }
};

The error I am getting in the chrome-dev-tool:

Uncaught TypeError: Cannot read property 'create' of undefined
    at Object.createLTR [as create] (ThemedStyleSheet.js?17e6:46)
    at WithStyles.maybeCreateStyles (withStyles.js?55c9:121)
    at WithStyles.componentWillMount (withStyles.js?55c9:107)
    at callComponentWillMount (react-dom.development.js?cada:6337)
    at mountClassInstance (react-dom.development.js?cada:6393)
    at updateClassComponent (react-dom.development.js?cada:7849)
    at beginWork (react-dom.development.js?cada:8233)
    at performUnitOfWork (react-dom.development.js?cada:10215)
    at workLoop (react-dom.development.js?cada:10279)
    at HTMLUnknownElement.callCallback (react-dom.development.js?cada:540)
The above error occurred in the <withStyles(SingleDatePicker)> component:
    in withStyles(SingleDatePicker) (created by ExpenseForm)
    in form (created by ExpenseForm)
    in div (created by ExpenseForm)
    in ExpenseForm (created by AddExpensePage)
    in div (created by AddExpensePage)
    in AddExpensePage (created by Route)
    in Route (created by AppRouter)
    in Switch (created by AppRouter)
    in div (created by AppRouter)
    in Router (created by BrowserRouter)
    in BrowserRouter (created by AppRouter)
    in AppRouter
    in Provider


问:
view data of recordset in immediate window
I have a recordset rst with 2 columns/fields ID and Value.  The recordset has multiple rows. While debugging, I am able to view records in the first row of the recordset in the immediate window using the following statements.

```<code>?rst.fields(0)
?rst.fields(1)
</code>```

But I am not able to view data in 2nd or 100th row?

答:
Leveraging answers from @Fionnualla and @codeling (and adding closing & cleanup for the recordset), also adding help from VBA: Debug.Print without newline? to make this look more like a table (still need to work on making the columns the actual width of the max size of the col).

This procedure will print out any query you drop onto it.

```<code>Public Sub debugPrintQuery(ByVal myQuery As String)
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset(myQuery)

' print column names
Dim i As Integer
For i = 0 To rs.Fields.Count - 2
    Debug.Print rs(i).Name & vbTab; 'print col names separated with a tab one from each other
Next i
Debug.Print rs(rs.Fields.Count - 1).Name 'last one without ; so it adds the newline

Do While Not rs.EOF
    For i = 0 To rs.Fields.Count - 2
        Debug.Print rs(i) & vbTab; 'print values separated with a tab one from each other
    Next i
    Debug.Print rs(rs.Fields.Count - 1) 'last one without ; so it adds the newline
    rs.MoveNext
Loop

rs.Close 'Close the recordset
Set rs = Nothing 'Clean up

End Sub
</code>```

Body:
I have a recordset rst with 2 columns/fields ID and Value.  The recordset has multiple rows. While debugging, I am able to view records in the first row of the recordset in the immediate window using the following statements.

?rst.fields(0)
?rst.fields(1)

But I am not able to view data in 2nd or 100th row?

Body:
Leveraging answers from @Fionnualla and @codeling (and adding closing & cleanup for the recordset), also adding help from VBA: Debug.Print without newline? to make this look more like a table (still need to work on making the columns the actual width of the max size of the col).

This procedure will print out any query you drop onto it.

Public Sub debugPrintQuery(ByVal myQuery As String)
Dim rs As DAO.Recordset
Set rs = CurrentDb.OpenRecordset(myQuery)

' print column names
Dim i As Integer
For i = 0 To rs.Fields.Count - 2
    Debug.Print rs(i).Name & vbTab; 'print col names separated with a tab one from each other
Next i
Debug.Print rs(rs.Fields.Count - 1).Name 'last one without ; so it adds the newline

Do While Not rs.EOF
    For i = 0 To rs.Fields.Count - 2
        Debug.Print rs(i) & vbTab; 'print values separated with a tab one from each other
    Next i
    Debug.Print rs(rs.Fields.Count - 1) 'last one without ; so it adds the newline
    rs.MoveNext
Loop

rs.Close 'Close the recordset
Set rs = Nothing 'Clean up

End Sub


问:
How do I add images to this random array?
I am wondering if it is possible to add images to the random generator so that when one clicks the button, a movie title AND a picture from the movie is displayed.

function GetValue()
{
    var myarray= new Array("The Santa Claus","Just Friends","Home Alone", "Home Alone 2","Serendipity","Love Actually","Elf","Christmas Vacation","A Christmas Story","The Grinch","Jingle All the Way","Rudolph the Red-Nosed Reindeer","Ernest Saves Christmas","Frosty the Snowman","The Muppet Christmas Carol","The Nightmare Before Christmas","Jesus of Nazareth 1977","Bad Santa");
    var random = myarray[Math.floor(Math.random() * myarray.length)];
    //alert(random);
    document.getElementById("message").innerHTML=random;
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#btnSearch {
  color: white;
  background-color: green;
  border: none;
  padding: 10px;
  font-family: verdana;
  font-weight: bold;

  }
h1 {
  text-shadow: -2px 0 green, 0 2px green, 2px 0 green, 0 -2px green;
}
body {
  background-image: url("http://www.publicdomainpictures.net/pictures/20000/velka/green-christmas-background.jpg");
}

#generator {
  display: block;
  margin: auto;
  text-align: center;
  background-color: #ff7878;
  border: solid;
  border-color: red;
  height: 250px;
  max-height: 250px;
}

.fa-snowflake-o {
  padding: 15px;
  color: white;

}

.fa-gift {
  padding: 15px;
  color: #ff0000;

}

.fa-tree {
  padding: 15px;
  color: #378b29;

}

#message {
  padding-top: 25px;
  padding-bottom: 25px;
  font-family: verdana;
  font-size: 20px;
  font-weight: bold;
}

.spin {
  -webkit-animation: spin 1s infinite linear;
  -moz-animation: spin 1s infinite linear;
  -o-animation: spin 1s infinite linear;
  animation: spin 5s infinite linear;
     -webkit-transform-origin: 50% 58%;
         transform-origin:50% 58%;
         -ms-transform-origin:50% 58%; /* IE 9 */
}

@-moz-keyframes spin {
  from {
    -moz-transform: rotate(0deg);
  }
  to {
    -moz-transform: rotate(360deg);
  }
}

@-webkit-keyframes spin {
  from {
    -webkit-transform: rotate(0deg);
  }
  to {
    -webkit-transform: rotate(360deg);
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}</code>```

<link
  href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"
  rel="stylesheet"  type='text/css'>

WHAT CHRISTMAS MOVIE SHOULD I WATCH?

<input type="button" id="btnSearch" value="What Christmas Movie Should I Watch?" onclick="GetValue();" />

```

答:
Just make it into a two dimensional array, then something like this should work.</p>

```<code>var arr = [
        ["Movie Name 1", "Picture URL 1"],
        ["Movie Name 2", "Picture URL 2"],
        ["Movie Name 3", "Picture URL 3"],
        ["Movie Name 4", "Picture URL 4"],
        ["Movie Name 5", "Picture URL 5"]
];
var random = myarray[Math.floor(Math.random() * myarray.length)];

document.getElementById("picture").src=random[1];
document.getElementById("message").innerHTML=random[0];
</code>```

Body:
I am wondering if it is possible to add images to the random generator so that when one clicks the button, a movie title AND a picture from the movie is displayed.

function GetValue()
{
    var myarray= new Array("The Santa Claus","Just Friends","Home Alone", "Home Alone 2","Serendipity","Love Actually","Elf","Christmas Vacation","A Christmas Story","The Grinch","Jingle All the Way","Rudolph the Red-Nosed Reindeer","Ernest Saves Christmas","Frosty the Snowman","The Muppet Christmas Carol","The Nightmare Before Christmas","Jesus of Nazareth 1977","Bad Santa");
    var random = myarray[Math.floor(Math.random() * myarray.length)];
    //alert(random);
    document.getElementById("message").innerHTML=random;
}

#btnSearch {
  color: white;
  background-color: green;
  border: none;
  padding: 10px;
  font-family: verdana;
  font-weight: bold;

  }
h1 {
  text-shadow: -2px 0 green, 0 2px green, 2px 0 green, 0 -2px green;
}
body {
  background-image: url("http://www.publicdomainpictures.net/pictures/20000/velka/green-christmas-background.jpg");
}

#generator {
  display: block;
  margin: auto;
  text-align: center;
  background-color: #ff7878;
  border: solid;
  border-color: red;
  height: 250px;
  max-height: 250px;
}

.fa-snowflake-o {
  padding: 15px;
  color: white;

}

.fa-gift {
  padding: 15px;
  color: #ff0000;

}

.fa-tree {
  padding: 15px;
  color: #378b29;

}

#message {
  padding-top: 25px;
  padding-bottom: 25px;
  font-family: verdana;
  font-size: 20px;
  font-weight: bold;
}

.spin {
  -webkit-animation: spin 1s infinite linear;
  -moz-animation: spin 1s infinite linear;
  -o-animation: spin 1s infinite linear;
  animation: spin 5s infinite linear;
     -webkit-transform-origin: 50% 58%;
         transform-origin:50% 58%;
         -ms-transform-origin:50% 58%; /* IE 9 */
}

@-moz-keyframes spin {
  from {
    -moz-transform: rotate(0deg);
  }
  to {
    -moz-transform: rotate(360deg);
  }
}

@-webkit-keyframes spin {
  from {
    -webkit-transform: rotate(0deg);
  }
  to {
    -webkit-transform: rotate(360deg);
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

<link
  href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"
  rel="stylesheet"  type='text/css'>

WHAT CHRISTMAS MOVIE SHOULD I WATCH?

<input type="button" id="btnSearch" value="What Christmas Movie Should I Watch?" onclick="GetValue();" />

Body:
Just make it into a two dimensional array, then something like this should work.

var arr = [
        ["Movie Name 1", "Picture URL 1"],
        ["Movie Name 2", "Picture URL 2"],
        ["Movie Name 3", "Picture URL 3"],
        ["Movie Name 4", "Picture URL 4"],
        ["Movie Name 5", "Picture URL 5"]
];
var random = myarray[Math.floor(Math.random() * myarray.length)];

document.getElementById("picture").src=random[1];
document.getElementById("message").innerHTML=random[0];


问:
How to install MuleSoft in RHEL 7?
Can anyone please summarize, how to install mulesoft runtime on RHEL step by step process ?
Suppose I have download tar file and extracted them , for running I have used under bin ./mule . Is this enough or I need to configure any additional datas etc ? How to archive this ?

答:
Below is the step for Mule 3.5.2, this can be used for other mule version too -

Steps -

Login to RHEL server.

Copy mmc-distribution-mule-console-bundle-3.5.2-HF1.tar.gz (downloaded from Mulesoft support portal) to /data/mule folder.
(In case of production setup, this file can be copied from Mule staging server from /home/ directory)

Go to /data/mule directory

Unzip mmc-distribution-mule-console-bundle-3.5.2-HF1.tar.gz using the following command
gunzip mmc-distribution-mule-console-bundle-3.5.2-HF1.tar.gz

Extract mmc-distribution-mule-console-bundle-3.5.2-HF1.tar using the following command
tar -xvf mmc-distribution-mule-console-bundle-3.5.2-HF1.tar

Move mule-enterprise-3.5.2 folder from mmc-distribution-mule-console-bundle-3.5.2-HF1 to the current directory ( /data/mule ) using the command
mv mmc-distribution-mule-console-bundle-3.5.2-HF1/mule-enterprise-3.5.2/ /data/mule

Delete the folder mmc-distribution-mule-console-bundle-3.5.2-HF1, as the remaining contents (MMC and other scripts) are not needed
rm -rf mmc-distribution-mule-console-bundle-3.5.2-HF1

Delete mmc-distribution-mule-console-bundle-3.5.2-HF1.tar file
rm mmc-distribution-mule-console-bundle-3.5.2-HF1.tar

Create a soft link /data/mule/mule-enterprise to point to /data/mule/mule-enterprise-3.5.2 using the following command.
ln -s mule-enterprise-3.5.2 mule-enterprise

Go to /home/ directory and change MULE_HOME environment variable in /home/.bash_profile, from /data/mule/mule-enterprise-3.5.0 to /data/mule/mule-enterprise

Execute the following command  (from /home/ directory)for having the latest value for MULE_HOME in the current context
source .bash_profile

Go to $MULE_HOME ( /data/mule/mule-enterprise ) and delete .mule folder
rm –rf .mule

Installing Enterprise Licence

Steps -

Copy the license file mule-ee-license.lic to $MULE_HOME/bin directory

Go to $MULE_HOME/bin  and run the following command to install license
mule -installLicense mule-ee-license.lic

Mule removes the trial license and replaces it with the enterprise edition license.  In the $MULE_HOME/conf directory, Mule saves a new file called muleLicenseKey.lic

To verify that Mule successfully installed your Enterprise license, run the following command

mule –verifyLicense
If the licence installation is successful, the following text is displayed in the output.
Valid license key --> Evaluation = false, Expiration Date = Wed Dec 31 00:00:00 GMT 2014, Contact Name = Sanjeet Pandey, Contact Email Address = sanjeetkumarpandey@gmail.com, Contact Telephone = 07831792088, Contact Company = PERSONAL, Contact Country = UK, Entitlements = clustering,datamapper

Title: How to install MuleSoft in RHEL 7?


问:
.length counts characters, not the array length
I want to count the items of an array returned by json. When I use response.length, it counts all the characters in the array(I guess so) while what I want it to do is to count how many items are there in the array. Same method works in another pages, just not with this one.

This is the php code:

```<code>            ...$response[] = array("id" => $row['appid'],
                            "hour" => $row['hour'],
                            "tname" => $tname,
                            "tsurname" => $tsurname,
                            "cname" => $cname,
                            "csurname" => $csurname,
                            "cgsm" => $cgsm,
                            "cemail" => $cemail,
                            "cdept" => $cdept,
                            "cdeg" => $cdeg,
                            "purpose" => $purpose,
                            "clientnotshown" => $row['clientnotshown']);

    };

    if(isset($response)){

    echo json_encode($response);

    } else {

    $response = array("val" => 0);
    echo json_encode($response);

    };
</code>```

Javascript code:

```<code>function updateTable() {

var getData = {
                      date: $("#displaydate").val(),
                      operation:"getData"
                  }

                  $.post( "printoperations.php", getData).done(function( response ) {
                      if (response.val != 0){

                          alert("so far so good")
                          var arrayLength = response.length
                          alert(response)
                          alert(arrayLength)}
};
</code>```

Here is a picture of what I get. I want to get the count of items, which in this case is 2.

答:
You should put this

header('Content-Type: application/json');

in your server side php query.

Body:
I want to count the items of an array returned by json. When I use response.length, it counts all the characters in the array(I guess so) while what I want it to do is to count how many items are there in the array. Same method works in another pages, just not with this one.

This is the php code:

            ...$response[] = array("id" => $row['appid'],
                            "hour" => $row['hour'],
                            "tname" => $tname,
                            "tsurname" => $tsurname,
                            "cname" => $cname,
                            "csurname" => $csurname,
                            "cgsm" => $cgsm,
                            "cemail" => $cemail,
                            "cdept" => $cdept,
                            "cdeg" => $cdeg,
                            "purpose" => $purpose,
                            "clientnotshown" => $row['clientnotshown']);

    };

    if(isset($response)){

    echo json_encode($response);

    } else {

    $response = array("val" => 0);
    echo json_encode($response);

    };

Javascript code:

function updateTable() {

var getData = {
                      date: $("#displaydate").val(),
                      operation:"getData"
                  }

                  $.post( "printoperations.php", getData).done(function( response ) {
                      if (response.val != 0){

                          alert("so far so good")
                          var arrayLength = response.length
                          alert(response)
                          alert(arrayLength)}
};

Here is a picture of what I get. I want to get the count of items, which in this case is 2.


问:
Will using LINQ to SQL help prevent SQL injection
I'm setting up a public site and the first thing on my mind is SQL injection. I have some text fields I'm saving and am using linq to update/write to the database. Am I safe using linq?

This example is creating the user account.

```<code>Data.MemberRegistrationDataContext context = new MemberRegistrationDataContext();
Data.tbl_Member_UserProfile profile = new tbl_Member_UserProfile();
profile.SSN = Convert.ToDecimal(Session["tempMemberSSN_Registration"]);
profile.UserName = userName;
profile.Password = password;
profile.EmailAddress = email;
profile.QuestionID = qID;
profile.QuestionResponse = securityAnswer;
profile.LastModDt = DateTime.Now;
profile.LastModBy = "web";
context.tbl_Member_UserProfiles.InsertOnSubmit(profile);
context.SubmitChanges();
</code>```

This example is changing the password

```<code>   MemberRegistrationDataContext dc = new MemberRegistrationDataContext();
   var mProfileRecord = dc.tbl_Member_UserProfiles.Single(c => c.SSN == sSSN);
   mProfileRecord.Password = sNewPassword;
   dc.SubmitChanges();
</code>```

Are these safe? Does LINQ parameterize the SQL it generates automatically?

答: It should because the SQL emitted uses named parameters which cannot be exploited to execute arbitrary SQL. </p>

Body:
I'm setting up a public site and the first thing on my mind is SQL injection. I have some text fields I'm saving and am using linq to update/write to the database. Am I safe using linq?

This example is creating the user account.

Data.MemberRegistrationDataContext context = new MemberRegistrationDataContext();
Data.tbl_Member_UserProfile profile = new tbl_Member_UserProfile();
profile.SSN = Convert.ToDecimal(Session["tempMemberSSN_Registration"]);
profile.UserName = userName;
profile.Password = password;
profile.EmailAddress = email;
profile.QuestionID = qID;
profile.QuestionResponse = securityAnswer;
profile.LastModDt = DateTime.Now;
profile.LastModBy = "web";
context.tbl_Member_UserProfiles.InsertOnSubmit(profile);
context.SubmitChanges();

This example is changing the password

   MemberRegistrationDataContext dc = new MemberRegistrationDataContext();
   var mProfileRecord = dc.tbl_Member_UserProfiles.Single(c => c.SSN == sSSN);
   mProfileRecord.Password = sNewPassword;
   dc.SubmitChanges();

Are these safe? Does LINQ parameterize the SQL it generates automatically?

OwnerDisplayName: Jan Bannister


问:
can not remove title bar in Activity
i want to remove title on top of my Activity. i tried this two way they work but not in api level 8.

1:

```<code><style name="NOtitleTheme" parent="Theme.AppCompat.Light">
<item name="android:windowFullscreen">true</item>
   <item name="android:windowNoTitle">true</item> </style>
</code>```

2:

```<code>this.requestWindowFeature(Window.FEATURE_NO_TITLE);
</code>```

any idea why this does not work on api 8?

once i managed to remove it in api 8, but i do not remember how.

EDIT:

Solved! the problem was     this.requestWindowFeature(Window.FEATURE_NO_TITLE) does not work on API 8, and also <item name="android:windowNoTitle">true</item> does not work, but   actionBar.hide() works , the reason that getSupportActionBar() returns null was using one of the two option before, i just forget to remove both. when i remove one i add other(what a a stupid !)
thanks all! (sorry for bad English)

答:
To me the only way that worked was doing this:

```<code><style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
</code>```

Only by saying that my theme was a child of NoActionBar, I managed to eliminate the actionBar. All the other ways failed. Don't know why.

Title: can not remove title bar in Activity

Body:
i want to remove title on top of my Activity. i tried this two way they work but not in api level 8.

1:

2:

this.requestWindowFeature(Window.FEATURE_NO_TITLE);

any idea why this does not work on api 8?

once i managed to remove it in api 8, but i do not remember how.

EDIT:

Solved! the problem was     this.requestWindowFeature(Window.FEATURE_NO_TITLE) does not work on API 8, and also <item name="android:windowNoTitle">true</item> does not work, but   actionBar.hide() works , the reason that getSupportActionBar() returns null was using one of the two option before, i just forget to remove both. when i remove one i add other(what a a stupid !)
thanks all! (sorry for bad English)

Body:
To me the only way that worked was doing this:

<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">

Only by saying that my theme was a child of NoActionBar, I managed to eliminate the actionBar. All the other ways failed. Don't know why.


问:
How to convert dates from several formats into one single format?
I have several different formats of dates in one field.  It looks like this.

```<code>20200228

12/15/2021

7/6/2020

Oct 29 2017 12:00AM

Oct 31 20

08/01/18
</code>```

How can I get everything standardized as MM/DD/YYYY?

```<code>20200228 --> 02/28/2020

12/15/2021 --> no change

Oct 31 2017 12:00AM --> 10/31/2017

Oct 31 20 --> 10/31/2017

08/01/18 --> 08/01/2018
</code>```

I tried all kinds of Cast and Convert combinations, but I couldn't get anything to work.  Does anyone out there have a solution for this?  It doesn't have to be one pass in one query.  I'm sure it can be done in several iterations, but I don't know how to tackle it.

答:
try this, it will help you--

UPDATE myTable
SET myDateColumn = CONVERT(DATETIME, myDateColumn, 103)
WHERE ISDATE(myDateColumn) = 0

Body:
I have several different formats of dates in one field.  It looks like this.

20200228

12/15/2021

7/6/2020

Oct 29 2017 12:00AM

Oct 31 20

08/01/18

How can I get everything standardized as MM/DD/YYYY?

20200228 --> 02/28/2020

12/15/2021 --> no change

Oct 31 2017 12:00AM --> 10/31/2017

Oct 31 20 --> 10/31/2017

08/01/18 --> 08/01/2018

I tried all kinds of Cast and Convert combinations, but I couldn't get anything to work.  Does anyone out there have a solution for this?  It doesn't have to be one pass in one query.  I'm sure it can be done in several iterations, but I don't know how to tackle it.


答:
```<code>var parseList = function(list){
  var result = [];
  for(var l2 of list){
    for(var el of l2){
      if(el !== Accounts) result.push(el);
    }
  }
  return result;
};
</code>```

or

```<code>list.map(el => el.length ? el[0] : el).filter(el => !Array.isArray(el) && el !== Accounts);
</code>```

Title: Create new list

Body:
Suppose I have the following list :

[["Accounts"],["Budget Propane"],[""],[""],[""],["Laser AMP"],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""]]

With a general function, how could I parse that list in such a way new list will become [account1, account2]?

So I need the remove all the subempty lists and the element [Accounts].

function isBlank(line) {
  return line[0].trim() === '';
}

function parseData(data) {

  const output = [];

  data.forEach(function(line, index) {
    if (isBlank(line) || index === 0) {
      return;
    }

    output.push(line[0])
  });

  return output;
}

console.log(parseData([["Accounts"],["Budget Propane"],[""],[""],[""],["Laser AMP"],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""],[""]]));

Body:
var parseList = function(list){
  var result = [];
  for(var l2 of list){
    for(var el of l2){
      if(el !== Accounts) result.push(el);
    }
  }
  return result;
};

or

list.map(el => el.length ? el[0] : el).filter(el => !Array.isArray(el) && el !== Accounts);