问:
Full screen scaling background image overlays
I have a page whose background image scales as the browser re-sizes. What I'm trying to figure out is how to make the blue marker image scale and maintain position in proportion to the background. For example, if the blue marker were on the tip of the harbor, as I scaled the browser down, I'd want that marker to stay on the tip of the harbor and shrink in size proportionally with the browser's new dimensions.

Anyone have any ideas that will point me in the right direction?

I used the below method to find the browser size, but I think my math's a little off. You can view the live example here:

http://mikeheavers.com/stage/full_screen_map/

The marker gets really off if you scale it in one direction more than the other.

```<code>    <style type="text/css">
        html {

                background: url(images/antigua.jpeg) no-repeat center center fixed;
                -webkit-background-size: cover;
                -moz-background-size: cover;
                -o-background-size: cover;
                background-size: cover;
        }

        #infoDiv {
            background: white;
            padding: 20px;
            width: 200px;
            position:absolute;
        }

        #map_canvas {
            position:absolute   ;
        }

        .marker {
            position:absolute;
            left: 800px;
            top: 400px;
            height: 20px;
            width: 20px;
            background: #ff0000;
        }

    </style>
    <script type="text/javascript" charset="utf-8" src="js/jquery-1.4.4.min.js"></script>

        <div id="infoDiv">

        </div>

        <div id="markers">
            <div class="marker">
            </div>
        </div>

        <script type="text/javascript">

            $(document).ready(function()
            {

                var myWidth = window.innerWidth;
                var leftVal = $("#markers").children().css('left');
                var leftValNumber = parseFloat(leftVal);
                var leftRatio = leftValNumber / myWidth;
                var leftValPos;

                var myHeight = window.innerHeight;
                var topVal = $("#markers").children().css('top');
                var topValNumber = parseFloat(topVal);
                var topRatio = topValNumber / myHeight;
                var topValPos;

                var scaleRatio;

                if (myWidth > myHeight){
                    scaleRatio = 20/myWidth;
                } else {
                    scaleRatio = 20/myHeight;
                }

                window.onresize = function() {

                    sizeMarkers();

                }

                function init()
                {

                    sizeMarkers();

                }

                function sizeMarkers()
                {

                      if( typeof( window.innerWidth ) == 'number' ) {
                        //Non-IE

                        myWidth = window.innerWidth;
                        myHeight = window.innerHeight;
                      } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
                        //IE 6+ in 'standards compliant mode'
                        myWidth = document.documentElement.clientWidth;
                        myHeight = document.documentElement.clientHeight;
                      } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
                        //IE 4 compatible
                        myWidth = document.body.clientWidth;
                        myHeight = document.body.clientHeight;
                      }
                        topVal = $("#markers").children().css('top');
                        topValNumber = parseFloat(topVal);
                        topValPos = topRatio * myHeight;

                        leftVal = $("#markers").children().css('top');
                        leftValNumber = parseFloat(leftVal);
                        leftValPos = leftRatio * myWidth;

                        if (myWidth < myHeight){
                            $("#markers").children().width(myWidth*scaleRatio);
                            $("#markers").children().height(myWidth*scaleRatio);
                        } else {
                            $("#markers").children().width(myHeight*scaleRatio);
                            $("#markers").children().height(myHeight*scaleRatio);
                        }

                        $("#markers").children().css('top',topValPos);
                        $("#markers").children().css('left',leftValPos);

                        $("#infoDiv").html( 'Width = ' + myWidth + ' | Height = ' + myHeight + ' | Top Value: ' + topValPos + ' | Left Value: ' + leftValPos);

                }

                init();

             });

        </script>
</code>```

答:
You could adjust width of your marker using JavaScript by keeping at any onresize events the same ratio marker-width and page-width.
To know your viewport width :
http://www.howtocreate.co.uk/tutorials/javascript/browserwindow

Hope it helps.


来源: stackexchange

问:
Merge Scala Seq
I have following Seq as input:

```<code>Seq(Seq(1,2),Seq(2,3),Seq(3,4),Seq(7,8),Seq(8,9))
</code>```

I would like to create another Seq from this like below:

```<code>Seq(Seq(1,4),Seq(7,9))
</code>```

I thought to use sliding operation (take 2) and merge as set to remove duplicates but I am not sure how to achieve it using Seq as it is immutable. Can someone help me?

答:
If I understand correctly, you want to remove all consecutive duplicate values, so that if you have Seq(..., (a, b), (b, c), ...) it returns Seq(..., (a, c), ...)

If you always have two elements in your inside Seqs, you should rather use pairs than Seq (because as much information known at compile time as possible should be given in the types), so I'll do it with pairs, and hopefully, you'll be able to adapt if needed.

```<code>def merge(l: Seq[(Int, Int)], acc: Seq[(Int, Int)] = Seq()): Seq[(Int, Int)] = l match {
  //if there's less than one element left, nothing can be merged
  case Seq() | Seq(_) => acc ++ l
  //if the first two elements are mergeable, merge them and call recursively (to allow merging the new pair with the next element)
  case (a, b) +: (c, d) +: tail if b == c => merge((a, d) +: tail, acc)
  //if the first two elements are not mergeable, put the first one in the accumulator, and carry on
  case p +: tail => merge(tail, acc :+ p)
}
</code>```

You can probably replace this tail-recursive function by a foldLeft, but I find it more readable this way.

ContentLicense: CC BY-SA 3.0

Title: Merge Scala Seq

Body:
I have following Seq as input:

Seq(Seq(1,2),Seq(2,3),Seq(3,4),Seq(7,8),Seq(8,9))

I would like to create another Seq from this like below:

Seq(Seq(1,4),Seq(7,9))

I thought to use sliding operation (take 2) and merge as set to remove duplicates but I am not sure how to achieve it using Seq as it is immutable. Can someone help me?

Body:
If I understand correctly, you want to remove all consecutive duplicate values, so that if you have Seq(..., (a, b), (b, c), ...) it returns Seq(..., (a, c), ...)

If you always have two elements in your inside Seqs, you should rather use pairs than Seq (because as much information known at compile time as possible should be given in the types), so I'll do it with pairs, and hopefully, you'll be able to adapt if needed.

def merge(l: Seq[(Int, Int)], acc: Seq[(Int, Int)] = Seq()): Seq[(Int, Int)] = l match {
  //if there's less than one element left, nothing can be merged
  case Seq() | Seq(_) => acc ++ l
  //if the first two elements are mergeable, merge them and call recursively (to allow merging the new pair with the next element)
  case (a, b) +: (c, d) +: tail if b == c => merge((a, d) +: tail, acc)
  //if the first two elements are not mergeable, put the first one in the accumulator, and carry on
  case p +: tail => merge(tail, acc :+ p)
}

You can probably replace this tail-recursive function by a foldLeft, but I find it more readable this way.


问:
Binary representation of a IP with inet_aton()
When I use inet_aton() like this

```<code>packed_ip_addr = socket.inet_aton(ip_addr)
</code>```

and print the value of packed IP:

```<code>print "Packed IP: %s" %packed_ip_addr
</code>```

Nothing shown in the screen. How can I print the exact binary format of IP address?

答:
Using str.format() and bytearray(), you can have the binary representation of this IP: 192.168.1.2 like below:

Both Python2 and Python3:

```<code>import socket

a = socket.inet_aton("192.168.1.2")
b = bytearray(a)
# If you don't want to have '0b' at the final output:
# c = '{0:b}'.format(int(''.join(map(str, b))))
c = '0b{0:b}'.format(int(''.join(map(str, b))))
# print(c)
print c

>>> '0b1001001010011100110101100'
</code>```

Body:
When I use inet_aton() like this

packed_ip_addr = socket.inet_aton(ip_addr)

and print the value of packed IP:

print "Packed IP: %s" %packed_ip_addr

Nothing shown in the screen. How can I print the exact binary format of IP address?

Body:
Using str.format() and bytearray(), you can have the binary representation of this IP: 192.168.1.2 like below:

Both Python2 and Python3:

import socket

a = socket.inet_aton("192.168.1.2")
b = bytearray(a)
# If you don't want to have '0b' at the final output:
# c = '{0:b}'.format(int(''.join(map(str, b))))
c = '0b{0:b}'.format(int(''.join(map(str, b))))
# print(c)
print c

>>> '0b1001001010011100110101100'


问:
Space Complexity of an array?
I have an array of size N, and N is <=200.

What would be the space complexity here.

O(1) or (N) - considering the constraint N.

答:
Complexity is only relevant when you try to foresee the performances of your algorithm with various input. I don't think it has any meaning to just speak about the space-complexity of an array without any context.

If you'll always create an array of size N (hard-coded), it's O(1), because no matter what input your algorithm crunches, the space taken by your array is the same.

If your N grows with the size of the input, it's O(f(n)), where f(n) is the relation between n (size of input) and N (size of array).

NOTE : the formulation O(...) is a mathematical symbol to represent magnitude without any regard to the multiplier (sorry for the lack of precision, I'm way over my math degree and never learned the english terms), so, if N is a constant, O(N) = O(1) (they have the exact same meaning).

And if I'm remembering it right, if f < C * g , O(f) = O(g). Thus, if N is < 200 , O(N) = O(200) = O(1)

Title: Space Complexity of an array?


问:
c# assign values from a for loop to individual variables
I have the value of Cell and Value in a for loop.  For example when i=0, value will be "first value" which I want to assign to A0Text.text. When i=1, , value will be "second value" which I want to assign to A1Text.text.. –

```<code>for (int i = 0; i < BLOCKS.Count; i++)
{
//possible values of Cell are A0, A1, A2 ...
var Cell = currentBLOCKData["cell"];

var Value = currentBLOCKData["value"];

....
</code>```

Then I have fields named with the same name as Cell

```<code>//possible cellName are - A0Text, A1text, A2Text .....
string cellName = Cell + "Text";
</code>```

I want to assign

```<code>A0Text.text = First value in above field - Value
A1Text.text = 2nd value in above field - Value
A2Text.text = 3rd value in above field - Value
</code>```

How can I make the above assigments?

答:
Gameobject.Find can be quite slow and I'd consider it pretty inefficient. Where you can avoid using it, try your best to. Why not create a public array for your Text components, assign them in the inspector and then iterate through your array in your loop.</p>

```<code>public Text[] textArray; //assign in inspector

for(int i = 0; i < BLOCKS.Count; i++){
    //.. your other code here
    textArray[i].text = Value.ToString();
}
</code>```

Body:
I have the value of Cell and Value in a for loop.  For example when i=0, value will be "first value" which I want to assign to A0Text.text. When i=1, , value will be "second value" which I want to assign to A1Text.text.. –

for (int i = 0; i < BLOCKS.Count; i++)
{
//possible values of Cell are A0, A1, A2 ...
var Cell = currentBLOCKData["cell"];

var Value = currentBLOCKData["value"];

....

Then I have fields named with the same name as Cell

//possible cellName are - A0Text, A1text, A2Text .....
string cellName = Cell + "Text";

I want to assign

A0Text.text = First value in above field - Value
A1Text.text = 2nd value in above field - Value
A2Text.text = 3rd value in above field - Value

How can I make the above assigments?

Body:
Gameobject.Find can be quite slow and I'd consider it pretty inefficient. Where you can avoid using it, try your best to. Why not create a public array for your Text components, assign them in the inspector and then iterate through your array in your loop.

public Text[] textArray; //assign in inspector

for(int i = 0; i < BLOCKS.Count; i++){
    //.. your other code here
    textArray[i].text = Value.ToString();
}


问:
What would be the fastest way to concatenate three files in C#?
I need to concatenate 3 files using C#. A header file, content, and a footer file, but I want to do this as cool as it can be done.

Cool = really small code or really fast (non-assembly code).

答:
If your files are text and not large, there's something to be said for dead-simple, obvious code. I'd use the following.

```<code>File.ReadAllText("file1") + File.ReadAllText("file2") + File.ReadAllText("file3");
</code>```

If your files are large text files and you're on Framework 4.0, you can use File.ReadLines to avoid buffering the entire file.

```<code>File.WriteAllLines("out", new[] { "file1", "file2", "file3" }.SelectMany(File.ReadLines));
</code>```

If your files are binary, See Mehrdad's answer

OwnerDisplayName: Bobby Bruckovnic

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: bdukes

Body:
If your files are text and not large, there's something to be said for dead-simple, obvious code. I'd use the following.

File.ReadAllText("file1") + File.ReadAllText("file2") + File.ReadAllText("file3");

If your files are large text files and you're on Framework 4.0, you can use File.ReadLines to avoid buffering the entire file.

File.WriteAllLines("out", new[] { "file1", "file2", "file3" }.SelectMany(File.ReadLines));

If your files are binary, See Mehrdad's answer

OwnerDisplayName: Jimmy

LastEditorDisplayName: Jimmy


问:
Android: callback for search widget opened and dismissed
I have a screen layout that is forced to be potrait mode. Because it is very complex I don't have the time right now to invest creating a separate one for landscape mode. It also doesn't make much sense for my type of application.

However, for input fields it's better to provide a landscape mode, because some phones have a hardware keyboard, which automatically aligns the phone in landscape and therefor makes it hard to look at the app that is still in portrait mode.

My solution to this is to put all text input into a dialog and temporarily enable landscape mode (if requested by the user) until the dialog is dismissed again.

This works perfectly. Except of the overlaying search widget (when pressing the search button from my application). I'm looking for two callbacks: one, when the search widget is raised (I cannot listen to the search button, because I sometimes raise it manually via a soft button) and when it is dismissed again (regardless if the search was finally triggered or canceled - it needs to work for both cases).

Any suggestions?

答:
There is an Activity callback for when search is activated. onSearchRequested()

For the dismiss/cancel of the search widget, you can add listeners via the SearchManager:

SearchManager.OnCancelListener

SearchManager.OnDismissListener

Get a reference to your SearchManager with:

```<code>context.getSystemService(Context.SEARCH_SERVICE)
</code>```

see getSystemService()

Body:
There is an Activity callback for when search is activated. onSearchRequested()

For the dismiss/cancel of the search widget, you can add listeners via the SearchManager:

SearchManager.OnCancelListener

SearchManager.OnDismissListener

Get a reference to your SearchManager with:

context.getSystemService(Context.SEARCH_SERVICE)

see getSystemService()


答:
try generate_series, smth like :

```<code>t=# with a as (
        with ali as (
                select g from generate_series('2017-06-08 01:24:00','2017-06-08 01:26:00','30 seconds'::interval) g
        )
        select g as t1, lead(g) over (order by g) t2
        from ali
        limit 4
)
select count(id), a.t1, coalesce(avg(id),0)
from a
left outer join logs l on l.query_date >= t1 and l.query_date <t2
group by a.t1
order by t1;
 count |           t1           |      coalesce
-------+------------------------+--------------------
     2 | 2017-06-08 01:24:00+00 | 2.5000000000000000
     3 | 2017-06-08 01:24:30+00 | 5.0000000000000000
     0 | 2017-06-08 01:25:00+00 |                  0
     0 | 2017-06-08 01:25:30+00 |                  0
(4 rows)
</code>```

updated to reconsile with OP notice - I used coalesce to "set default value to zero" for rows where avg() returns NULL

Title: How to divide time period to parts?

Body:
There is a column in the table that stores the time when the record was created. The query specifies the end and start dates, then the interval is divided into n parts. And within each gap I need to calculate the number of records from the database.
Tell me what to add to the query. Also, I need to count the number of records even if they were not at that time.

F.e.

----------------------------
 id |      query date      |
----------------------------
1   | 2017-06-08 01:23:00  |
2   | 2017-06-08 01:24:19  |
3   | 2017-06-08 01:24:21  |
4   | 2017-06-08 01:24:36  |
5   | 2017-06-08 01:24:37  |
6   | 2017-06-08 01:24:41  |
----------------------------

I choose period from 2017-06-08 01:24:00 to 2017-06-08 01:26:00 and devide this period to 4 parts, then I wait for

------------------------------
 count |      query date      |
------------------------------
2      | 2017-06-08 01:24:00  |
3      | 2017-06-08 01:24:30  |
0      | 2017-06-08 01:25:00  |
0      | 2017-06-08 01:25:30  |
------------------------------

My start

select to_timestamp(extract(epoch from query_date)/extract(epoch FROM age('2017-06-08 01:25:00', '2017-06-08 01:24:00'))/60), count(*) from logs group by extract(epoch from query_date)/extract(epoch FROM age('2017-06-08 01:25:00', '2017-06-08 01:24:00'))/60;

Body:
try generate_series, smth like :

t=# with a as (
        with ali as (
                select g from generate_series('2017-06-08 01:24:00','2017-06-08 01:26:00','30 seconds'::interval) g
        )
        select g as t1, lead(g) over (order by g) t2
        from ali
        limit 4
)
select count(id), a.t1, coalesce(avg(id),0)
from a
left outer join logs l on l.query_date >= t1 and l.query_date <t2
group by a.t1
order by t1;
 count |           t1           |      coalesce
-------+------------------------+--------------------
     2 | 2017-06-08 01:24:00+00 | 2.5000000000000000
     3 | 2017-06-08 01:24:30+00 | 5.0000000000000000
     0 | 2017-06-08 01:25:00+00 |                  0
     0 | 2017-06-08 01:25:30+00 |                  0
(4 rows)

updated to reconsile with OP notice - I used coalesce to "set default value to zero" for rows where avg() returns NULL


问:
Jenkins: deploy to AWS ECS with docker compose
I have some misunderstanding. I have Jenkins instance, ESC cluster and docker-compose config file to compose my images and link up containers.

After git push my Jenkins instance grabs all sources from all repos (webapp, api, lb) and makes a batch of operations like build, copy files and etc.

After that I have all folders with Dockerfiles in state "ready for compose".

And in this stage I cant get how I should ping my ESC cluster on AWS to grab all images from Jenkins and compose them with my docker-compose.yml config.

I would be glad of any useful information.

Thanks.

答:
First, you need to push your images from the Jenkins server into ECR. Push every image individually to an independent repo.

Next, you have to create an ECS cluster. In this cluster, you create an ECS service that runs in the cluster. For this Service, you create and configure a Task Definition to run your linked containers. You don't need to use docker-compose for this: in ECS you define the links between containers in the configuration of the Task Definition. You can add several container definitions to the same Task Definition, and ECS will link them together.

You can automate all of this from your Jenkins server by attaching an Instance Profile to it that allows it to call the ECS API. In order to deploy new images, all you need to do is pushing them to their ECR repos, and create a new Task Definition pointing to them, and update the service that runs these task definitions. ECS will automatically trigger a blue-green deployment on your behalf.


问:
Cut off all non-numeric values in a column
Is there a way in Excel or in VBA to filter the cell by his character and then insert it into a separate column?

For example, my data looks like this:

```<code>A3200,12
AB2000,32
-300,34
32567,32A
6745,21AB
500+
</code>```

And I want that the result be like this:

```<code>Column A
3200,12
2000,23
300,34
32567,32
6745,21
500

Column B
A
AB
-
A
AB
+
</code>```

So is there a way to go thorugh each cell and cut off all non-numeric values out of These and copy them into another column?

答:
One way to do it is to create UDF (User-Difined Function).

Place 2 following functions into a VBA Module:

```<code>Function Digits(s As String) As String
     With CreateObject("vbscript.regexp")
        .Pattern = "[^0-9,]"
        .Global = True
        Digits = .Replace(s, "")
    End With
End Function

Function NonDigits(s As String) As String
   With CreateObject("vbscript.regexp")
      .Pattern = "[0-9,]"
      .Global = True
      NonDigits = .Replace(s, "")
   End With
End Function
</code>```

To use these functions: if you data is in cell A1, just type formula in cell B1

```<code>=Digits(A1)
</code>```

and in cell C1:

```<code>=NonDigits(A1)
</code>```

The first will return your data as text containing digits only. To convert it to a number, use VALUE function.

The second returns your data without any digits.

Body:
Is there a way in Excel or in VBA to filter the cell by his character and then insert it into a separate column?

For example, my data looks like this:

A3200,12
AB2000,32
-300,34
32567,32A
6745,21AB
500+

And I want that the result be like this:

Column A
3200,12
2000,23
300,34
32567,32
6745,21
500

Column B
A
AB
-
A
AB
+

So is there a way to go thorugh each cell and cut off all non-numeric values out of These and copy them into another column?

Body:
One way to do it is to create UDF (User-Difined Function).

Place 2 following functions into a VBA Module:

Function Digits(s As String) As String
     With CreateObject("vbscript.regexp")
        .Pattern = "[^0-9,]"
        .Global = True
        Digits = .Replace(s, "")
    End With
End Function

Function NonDigits(s As String) As String
   With CreateObject("vbscript.regexp")
      .Pattern = "[0-9,]"
      .Global = True
      NonDigits = .Replace(s, "")
   End With
End Function

To use these functions: if you data is in cell A1, just type formula in cell B1

=Digits(A1)

and in cell C1:

=NonDigits(A1)

The first will return your data as text containing digits only. To convert it to a number, use VALUE function.

The second returns your data without any digits.


问:
How to send an array of test-cases to PHPUnit willReturnOnConsecutiveCalls
I am trying to send a pre-calculated array of test cases into a mock to be returned on consecutive calls - similar to the map function. However it takes a list of arguments, not an array.

My array is already generated by a fixture-generator and may be of variable length.

What I want to do is something like this, but of course this causes it to return the entire array on the first call.

```<code>// In a test case:
$processorMock
    ->method('process')
    ->willReturnOnConsecutiveCalls(
        $fixtureLoader->getProcessorScenarios() // how to explode this?
    );

// class FixtureLoader pseudocode:
function getProcessorScenarios(){
    return [
       [ $param1, $param2, $param3 ], // case 1
       [ $param1, $param2, $param3 ], // case 2
       ...
       [ $param1, $param2, $param3 ], // case N
    ];
}
</code>```

I want to destructure the returned array from the fixture loader, using list() or some var-args exploding language construct like "..." in other languages, but couldn't find anything native that worked.

I do have what feels like a hacky method, which I will post as an initial answer Q&A style.  I want to know if it's the best method.

答:
A friend suggested an alternative available in PHP 5.6 - the "splat" operator or elipsis (...) although it doesn't seem to have an official name in PHP, but is a form of destructuring like the "spread" operator in Javascript ES6.

While I haven't tested this (as my app is currently locked to PHP 5.4 due to environmental constraints), it should therefore work simply thus:

```<code>$processorMock
    ->method('process')
    ->willReturnOnConsecutiveCalls(
        ...$fixtureLoader->getProcessorScenarios()
);
</code>```

This is definitely the sweeter alternative I was looking for.

Body:
I am trying to send a pre-calculated array of test cases into a mock to be returned on consecutive calls - similar to the map function. However it takes a list of arguments, not an array.

My array is already generated by a fixture-generator and may be of variable length.

What I want to do is something like this, but of course this causes it to return the entire array on the first call.

// In a test case:
$processorMock
    ->method('process')
    ->willReturnOnConsecutiveCalls(
        $fixtureLoader->getProcessorScenarios() // how to explode this?
    );

// class FixtureLoader pseudocode:
function getProcessorScenarios(){
    return [
       [ $param1, $param2, $param3 ], // case 1
       [ $param1, $param2, $param3 ], // case 2
       ...
       [ $param1, $param2, $param3 ], // case N
    ];
}

I want to destructure the returned array from the fixture loader, using list() or some var-args exploding language construct like "..." in other languages, but couldn't find anything native that worked.

I do have what feels like a hacky method, which I will post as an initial answer Q&A style.  I want to know if it's the best method.

Body:
A friend suggested an alternative available in PHP 5.6 - the "splat" operator or elipsis (...) although it doesn't seem to have an official name in PHP, but is a form of destructuring like the "spread" operator in Javascript ES6.

While I haven't tested this (as my app is currently locked to PHP 5.4 due to environmental constraints), it should therefore work simply thus:

$processorMock
    ->method('process')
    ->willReturnOnConsecutiveCalls(
        ...$fixtureLoader->getProcessorScenarios()
);

This is definitely the sweeter alternative I was looking for.


问:
Session from javascript
I'd like to inspect the session variable.  Best case something that works in the firebugs little interpreter, but if I have to put it in the file thats fine.  Right now I just made a short PHP to output $_SESSION, but if I could find something analogous to be done right in the browser that would be ideal.  document.cookie doesn't seem to do what im looking for, at least not that i see.

Basically looking for something analogous to $_SESSION that I can use in javascript

EDIT - was trying to see if i could get anything more than, or extract the meaning  PHPSESSID=o147cf52u9d7qr251hc3n6ilu2; ASESSIONID=101wvpe-3FA77F204CFF55BA61E696AD3F62F0F8 on the client-side.   As it stands I guess i can just write a small ajax function to a url that echos the session.  Thanks for the help!

PS - Do those document.cookie values have anything to do with whats inside the session, or are they just identifiers to tell one session from another?

答: I am using FirePHP to debug variables from my Ajax calls, maybe it is what you are looking for?</p>

Title: Session from javascript


问:
Circular dependency error while trying to add reference
In my solution, there are 2 projects: Helper and Service.Helper project has a reference to the service

In the helper project I have

Culture Helper

```<code> public static class CultureHelper
    {
    public static Location GetLocationBasedOnCulture(string cultureName)
            {
                Location location = Location.UK;
                if (cultureName == Constants.CultureConstants.Italy)
                {
                    location = Location.Italy;
                }
                return location;
            }
    }
</code>```

Culture Constants:

```<code>public static class CultureConstants
    {
        public static readonly string UK = "en-GB";
        public static readonly string Italy = "it-IT";

    }
</code>```

In the Service I am trying to add this method:

```<code>public Enum DetermineLocation()
        {
            var culture = CultureHelper.GetCurrentCulture();
            Location location = CultureHelper.GetLocationBasedOnCulture(culture);
            return location;
        }
</code>```

I am trying to add a method to the service that uses the static CultureHelper class but I am unable to add a reference to helper in service as it will lead to circular dependency. How do I go ahead with this. Is creating an interface going to solve this problem and how.

答:
If your projects do genuinely need to cross-reference each other, and you're unable to use the other suggestions to restructure, here's a demo of how you can achieve mutual cross-referencing.

In Visual Studio, create a new Solution and add a normal Class Library called A. Leave Class1 alone.

Create a Shared Project and name it Proto_B. Add a class called Class1 and change its namespace declaration to be B.

Create a Class Library called B_NonA. Delete Class1. Add a shared project reference to Proto_B, and change the settings so that its default namespace is B and it emits the B assembly. Add a reference from project A to project B_NonA.

Create a Class Library called B_A. Delete Class1. Add a shared project reference to Proto_B, and change the settings so that its default namespace is B and it emits the B assembly. Also set it to include a conditional compilation symbol HASA for all configurations. Add a reference from project B_A to project A.

All of the code can now compile. The assemblies that you would distribute would be those emitted by the A and B_A projects.

You never add code to B_A or B_NonA, only to ProtoB. Where code has to actually make use of A assembly features, that code should be wrapped in an #if HASA block.

In this toy example, A.Class1 is:

```<code>namespace A
{
    public class Class1
    {
        private static B.Class1 _otherB = new B.Class1();
    }
}
</code>```

And B.Class1 in ProtoB is:

```<code>namespace B
{
    public class Class1
    {
#if HASA
        private static A.Class1 _otherA = new A.Class1();
#endif
    }
}
</code>```

One obvious downside to this approach is that it leads to longer build times since any change in B requires B to be rebuilt twice with a build of A performed in between.

Body:
In my solution, there are 2 projects: Helper and Service.Helper project has a reference to the service

In the helper project I have

Culture Helper

 public static class CultureHelper
    {
    public static Location GetLocationBasedOnCulture(string cultureName)
            {
                Location location = Location.UK;
                if (cultureName == Constants.CultureConstants.Italy)
                {
                    location = Location.Italy;
                }
                return location;
            }
    }

Culture Constants:

public static class CultureConstants
    {
        public static readonly string UK = "en-GB";
        public static readonly string Italy = "it-IT";

    }

In the Service I am trying to add this method:

public Enum DetermineLocation()
        {
            var culture = CultureHelper.GetCurrentCulture();
            Location location = CultureHelper.GetLocationBasedOnCulture(culture);
            return location;
        }

I am trying to add a method to the service that uses the static CultureHelper class but I am unable to add a reference to helper in service as it will lead to circular dependency. How do I go ahead with this. Is creating an interface going to solve this problem and how.

Body:
If your projects do genuinely need to cross-reference each other, and you're unable to use the other suggestions to restructure, here's a demo of how you can achieve mutual cross-referencing.

In Visual Studio, create a new Solution and add a normal Class Library called A. Leave Class1 alone.

Create a Shared Project and name it Proto_B. Add a class called Class1 and change its namespace declaration to be B.

Create a Class Library called B_NonA. Delete Class1. Add a shared project reference to Proto_B, and change the settings so that its default namespace is B and it emits the B assembly. Add a reference from project A to project B_NonA.

Create a Class Library called B_A. Delete Class1. Add a shared project reference to Proto_B, and change the settings so that its default namespace is B and it emits the B assembly. Also set it to include a conditional compilation symbol HASA for all configurations. Add a reference from project B_A to project A.

All of the code can now compile. The assemblies that you would distribute would be those emitted by the A and B_A projects.

You never add code to B_A or B_NonA, only to ProtoB. Where code has to actually make use of A assembly features, that code should be wrapped in an #if HASA block.

In this toy example, A.Class1 is:

namespace A
{
    public class Class1
    {
        private static B.Class1 _otherB = new B.Class1();
    }
}

And B.Class1 in ProtoB is:

namespace B
{
    public class Class1
    {
#if HASA
        private static A.Class1 _otherA = new A.Class1();
#endif
    }
}

One obvious downside to this approach is that it leads to longer build times since any change in B requires B to be rebuilt twice with a build of A performed in between.


问:
How to bind date and time separately?
I want to bind date and time separately in a controller. I have 1 timepicker and 1 datepicker on a form, i use InitBinder binder for time picker which is,

```<code>@InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setLenient(true);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }
</code>```

But this doesn't work for both time picker and date picker. any better suggestion please....

答:
Try this with your code:

```<code>@InitBinder
void allowFields(WebDataBinder webDataBinder){
    webDataBinder.setAllowedFields("date");
    webDataBinder.setAllowedFields("time");
}
</code>```

and use this in your POJO:

```<code>  @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
  private Date date;
</code>```

Title: How to bind date and time separately?

Body:
I want to bind date and time separately in a controller. I have 1 timepicker and 1 datepicker on a form, i use InitBinder binder for time picker which is,

@InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setLenient(true);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(sdf, true));
    }

But this doesn't work for both time picker and date picker. any better suggestion please....

Body:
Try this with your code:

@InitBinder
void allowFields(WebDataBinder webDataBinder){
    webDataBinder.setAllowedFields("date");
    webDataBinder.setAllowedFields("time");
}

and use this in your POJO:

  @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME)
  private Date date;


问:
Need to add fade in to image om slideshow
I need to add a fade in and fade out annimation to my image on existing code for slide show. The images must fade in /fade out when user click the buttons. Here is my code.

HTML:

```<code><div id="imageSlider">
</code>```

```<code>  <button id="prevBTN" onclick="prev()"> <b>Prev</b> </button>

  <button id="nextBTN" onclick="next()"> <b>Next</b> </button>
</div>
</code>```

Javascript:

```<code>var images = [
  "HTMLcert.jpg",
  "CSScert.jpg",
  "javaScriptCert.jpg",
  "PHPcert.jpg"
];

var num = 0;

function next() {
  var slider =
    document.getElementById("slider");
  num++;
  if (num >= images.length) {
    num = 0;
  }
  slider.src = images[num];
}

function prev() {
  var slider =
    document.getElementById("slider");
  num--;
  if (num <= 0) {
    num = images.length - 1;
  }
  slider.src = images[num];
}
</code>```

how can I add fade in and out to existing java script code .

答:
You can do it using CSS3 annimation , by creating a custom animation , add a class using this last  then toggle the class while clicking in the buttons .

bellow a working snippet :

var images = [
  "http://ramg1.net/images/3.jpg",
  "https://www.gregbowe.com/assets/img/htmlcert.jpg",
  "http://www.lordlamer.de/wp-content/uploads/2011/02/php-cert.jpg",
  "http://www.michellekeselgiancola.com/images/certs/uploads/phpcert.jpg"
];

var num = 0;

function next() {
  var slider =
    document.getElementById("slider");
  num++;
  if (num >= images.length) {
    num = 0;
  }

  slider.classList.remove("fade");
  slider.src = images[num];
  setTimeout(function(){slider.classList.add("fade");},10);
  //slider.classList.add("fade");
}

function prev() {
  var slider =
    document.getElementById("slider");
  num--;
  if (num <= 0) {
    num = images.length - 1;
  }

  slider.classList.remove("fade");
  slider.src = images[num];
  setTimeout(function(){slider.classList.add("fade");},10);
  //slider.classList.add("fade");
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>/* create the fade custom annimation wich set 0 to 1 opacity on an element */
@-webkit-keyframes fade {
  0%   { opacity: 0; }
  100% { opacity: 1; }
}
@-moz-keyframes fade {
  0%   { opacity: 0; }
  100% { opacity: 1; }
}
@-o-keyframes fade {
  0%   { opacity: 0; }
  100% { opacity: 1; }
}
@keyframes fade {
  0%   { opacity: 0; }
  100% { opacity: 1; }
}

/* create the class that trigger the annimation */
.fade {
  -webkit-animation: fade 2s ease; /* Safari 4+ */
  -moz-animation:    fade 2s ease; /* Fx 5+ */
  -o-animation:      fade 2s ease; /* Opera 12+ */
  animation:         fade 2s ease; /* IE 10+, Fx 29+ */
}</code>```

  <button id="prevBTN" onclick="prev()"> Prev </button>

  <button id="nextBTN" onclick="next()"> Next </button>

```

Body:
I need to add a fade in and fade out annimation to my image on existing code for slide show. The images must fade in /fade out when user click the buttons. Here is my code.

HTML:

  <button id="prevBTN" onclick="prev()"> Prev </button>

  <button id="nextBTN" onclick="next()"> Next </button>

Javascript:

var images = [
  "HTMLcert.jpg",
  "CSScert.jpg",
  "javaScriptCert.jpg",
  "PHPcert.jpg"
];

var num = 0;

function next() {
  var slider =
    document.getElementById("slider");
  num++;
  if (num >= images.length) {
    num = 0;
  }
  slider.src = images[num];
}

function prev() {
  var slider =
    document.getElementById("slider");
  num--;
  if (num <= 0) {
    num = images.length - 1;
  }
  slider.src = images[num];
}

how can I add fade in and out to existing java script code .

Body:
You can do it using CSS3 annimation , by creating a custom animation , add a class using this last  then toggle the class while clicking in the buttons .

bellow a working snippet :

var images = [
  "http://ramg1.net/images/3.jpg",
  "https://www.gregbowe.com/assets/img/htmlcert.jpg",
  "http://www.lordlamer.de/wp-content/uploads/2011/02/php-cert.jpg",
  "http://www.michellekeselgiancola.com/images/certs/uploads/phpcert.jpg"
];

var num = 0;

function next() {
  var slider =
    document.getElementById("slider");
  num++;
  if (num >= images.length) {
    num = 0;
  }

  slider.classList.remove("fade");
  slider.src = images[num];
  setTimeout(function(){slider.classList.add("fade");},10);
  //slider.classList.add("fade");
}

function prev() {
  var slider =
    document.getElementById("slider");
  num--;
  if (num <= 0) {
    num = images.length - 1;
  }

  slider.classList.remove("fade");
  slider.src = images[num];
  setTimeout(function(){slider.classList.add("fade");},10);
  //slider.classList.add("fade");
}

/* create the fade custom annimation wich set 0 to 1 opacity on an element */
@-webkit-keyframes fade {
  0%   { opacity: 0; }
  100% { opacity: 1; }
}
@-moz-keyframes fade {
  0%   { opacity: 0; }
  100% { opacity: 1; }
}
@-o-keyframes fade {
  0%   { opacity: 0; }
  100% { opacity: 1; }
}
@keyframes fade {
  0%   { opacity: 0; }
  100% { opacity: 1; }
}

/* create the class that trigger the annimation */
.fade {
  -webkit-animation: fade 2s ease; /* Safari 4+ */
  -moz-animation:    fade 2s ease; /* Fx 5+ */
  -o-animation:      fade 2s ease; /* Opera 12+ */
  animation:         fade 2s ease; /* IE 10+, Fx 29+ */
}

<div id="imageSlider">

  <img id="slider" class="fade" src="http://ramg1.net/images/3.jpg" width="400px" height="80%" />

  <button id="prevBTN" onclick="prev()"> <b>Prev</b> </button>

  <button id="nextBTN" onclick="next()"> <b>Next</b> </button>
</div>


问:
Can't edit cell Values after clicking Excel button
I have a macro that removes a line from a named range.

After pressing the button to run that macro, I can't edit cells anymore.

Not in that range, nor in any editable cells in my protected worksheet.

Seems that workbook with the same code didn't work in Excel 2010 too.

This is my macro :

```<code>Sub DeleteParameterRow(ByVal tCell As Range)

    '''this procedure delete a row from one of the parameters lists
    On Error GoTo ErrHandler

    Application.EnableEvents = False
    Application.DisplayAlerts = False

    Dim iRowToDelete As Integer

    Call Unprotect_All()

    If IsPartOfRange(tCell, NamedRange("Param_ParametersList"), False) Then

        tCell.Delete Shift:=xlUp

    Else

        MsgBox("Please select one of the parameters list", vbInformation, "Error")

    End If

EndProc:
    Call Protect_All()
    Application.DisplayAlerts = True
    Application.EnableEvents = True
    Exit Sub

ErrHandler:
    MsgBox(Err.Description, vbCritical, Err.Number)
    GoTo EndProc

End Sub

Function IsPartOfRange(ByVal rSearchRange As Range, ByVal rSearchInRange As Range, ByVal bIsEntireRange As Boolean) As Boolean
    '''this function gets a small range, a big range and if it is supposed to be the entire range, and check
    '''if the smaller range is part of the bigger one, and if it is  the entire range
    IsPartOfRange = False

    If Not Intersect(rSearchRange, rSearchInRange) Is Nothing Then

        If bIsEntireRange = True Then

            If rSearchRange.Address = rSearchInRange.MergeArea.Address Then IsPartOfRange = True

        Else

            IsPartOfRange = True

        End If

    End If

End Function
</code>```

答:
See my last comment were I mentioned it seems to be a kind of "Refresh" problem.

 After code runs something is stacked in Excel that prevents edits. ( No way to report bugs to MS... :(
)

To force a "Refresh" programmatically I found clearing the content of an arbitrarily cell is usefull.
 So Adding the line tCell.ClearContents befor EndProc: did the trik.

Body:
I have a macro that removes a line from a named range.

After pressing the button to run that macro, I can't edit cells anymore.

Not in that range, nor in any editable cells in my protected worksheet.

Seems that workbook with the same code didn't work in Excel 2010 too.

This is my macro :

Sub DeleteParameterRow(ByVal tCell As Range)

    '''this procedure delete a row from one of the parameters lists
    On Error GoTo ErrHandler

    Application.EnableEvents = False
    Application.DisplayAlerts = False

    Dim iRowToDelete As Integer

    Call Unprotect_All()

    If IsPartOfRange(tCell, NamedRange("Param_ParametersList"), False) Then

        tCell.Delete Shift:=xlUp

    Else

        MsgBox("Please select one of the parameters list", vbInformation, "Error")

    End If

EndProc:
    Call Protect_All()
    Application.DisplayAlerts = True
    Application.EnableEvents = True
    Exit Sub

ErrHandler:
    MsgBox(Err.Description, vbCritical, Err.Number)
    GoTo EndProc

End Sub

Function IsPartOfRange(ByVal rSearchRange As Range, ByVal rSearchInRange As Range, ByVal bIsEntireRange As Boolean) As Boolean
    '''this function gets a small range, a big range and if it is supposed to be the entire range, and check
    '''if the smaller range is part of the bigger one, and if it is  the entire range
    IsPartOfRange = False

    If Not Intersect(rSearchRange, rSearchInRange) Is Nothing Then

        If bIsEntireRange = True Then

            If rSearchRange.Address = rSearchInRange.MergeArea.Address Then IsPartOfRange = True

        Else

            IsPartOfRange = True

        End If

    End If

End Function


问:
onclick slide to page down not working
In this website

www.homepreneurawards.com

when navbar menu is clicked it wont slide to the specific div content what could be the issue

```<code> <header class="header type-1">
        <div class="container">
            <div class="logo-block">
                <a class="logo" href="#"><img src="http://homepreneurawards.com/Homepreneur/img/logo.gif" alt=""></a>
            </div>
            <nav class="main-nav">
                <ul class="anchor-navigation">
                    <li><a class="anchor-scroll" href="#aboutbrandavatar">ABOUT</a></li>
                    <li><a class="anchor-scroll" href="#whoishomepreneur">HOMEPRENEUR ?</a></li>
                    <li><a class="anchor-scroll" href="#categories">CATEGORIES</a></li>
                    <li><a class="anchor-scroll" href="#jurymembers">JURY MEMBERS</a></li>
                    <li><a class="anchor-scroll" href="#timeline">PROCESS FLOW</a></li>
                    <li><a class="anchor-scroll" href="#organizers">ORGANIZERS</a></li>
                    <li><a class="anchor-scroll" href="#sponsorspartners">SPONSORS</a></li>
                    <li><a class="anchor-scroll" href="#partnerscontent">PARTNERS</a></li>
                    <li><a class="anchor-scroll" href="#contact">CONTACT US</a></li>
                </ul>
            </nav>
            <button class="cmn-toggle-switch"><span></span></button>
        </div>
    </header>
</code>```

答:
The problem is in your function in anchors.navigation.js

```<code>function setImmediateAnchor(anchorObject, time) {
    scrollFlag = 1;
    if (currentAnchor) {  -- THIS LINE
        $('html,body').stop().animate({
            'scrollTop': contentTop[anchorObject.attr('href')].top
        }, time, function() {
            $(scrollLinkSelector).parent().removeClass('active');
            anchorObject.parent().addClass('active');
            window.location.hash = '#/' + anchorObject.attr('href').substr(1);
            currentAnchor = anchorObject.attr('href');
            scrollFlag = 0;
        });
    }
}
</code>```

The condition if (currentAnchor) is failing because currentAnchor is empty. You have set it to  currentAnchor = window.location.hash.replace('/', '') which will be empty when your page is loaded because you does not have anything in url after http://www.homepreneurawards.com

There are 2 solution for it which ever you find feasible.

Add a condition below your initialization code to check if currentAnchor is empty then set it to some value say "#initialized" like below.

```<code>    var contentTop = {},
    contentOffset = 87,
    currentAnchor = window.location.hash.replace('/', ''),
    scrollFlag = 0,
    scrollLinkSelector = '.anchor-scroll';

    -- add this condition.
    if(currentAnchor =='')
    {
     currentAnchor = '#initialized';
    }
</code>```

You can simply check for empty values in you function setImmediateAnchor like below notice 3rd line and handle empty values.

```<code>   function setImmediateAnchor(anchorObject, time) {
    scrollFlag = 1;
    if (currentAnchor == '' || currentAnchor) {  -- THIS LINE
        $('html,body').stop().animate({
            'scrollTop': contentTop[anchorObject.attr('href')].top
        }, time, function() {
            $(scrollLinkSelector).parent().removeClass('active');
            anchorObject.parent().addClass('active');
            window.location.hash = '#/' + anchorObject.attr('href').substr(1);
            currentAnchor = anchorObject.attr('href');
            scrollFlag = 0;
        });
    }
}
</code>```

Or you can use any other feasible way, the core problem lies in that condition that does not allow you to scroll since your variable is empty. You can fix either way which you find feasible.

Title: onclick slide to page down not working

Body:
In this website

www.homepreneurawards.com

when navbar menu is clicked it wont slide to the specific div content what could be the issue

ABOUT

HOMEPRENEUR ?

CATEGORIES

JURY MEMBERS

PROCESS FLOW

ORGANIZERS

SPONSORS

PARTNERS

CONTACT US

            <button class="cmn-toggle-switch"></button>

Body:
The problem is in your function in anchors.navigation.js

function setImmediateAnchor(anchorObject, time) {
    scrollFlag = 1;
    if (currentAnchor) {  -- THIS LINE
        $('html,body').stop().animate({
            'scrollTop': contentTop[anchorObject.attr('href')].top
        }, time, function() {
            $(scrollLinkSelector).parent().removeClass('active');
            anchorObject.parent().addClass('active');
            window.location.hash = '#/' + anchorObject.attr('href').substr(1);
            currentAnchor = anchorObject.attr('href');
            scrollFlag = 0;
        });
    }
}

The condition if (currentAnchor) is failing because currentAnchor is empty. You have set it to  currentAnchor = window.location.hash.replace('/', '') which will be empty when your page is loaded because you does not have anything in url after http://www.homepreneurawards.com

There are 2 solution for it which ever you find feasible.

Add a condition below your initialization code to check if currentAnchor is empty then set it to some value say "#initialized" like below.

    var contentTop = {},
    contentOffset = 87,
    currentAnchor = window.location.hash.replace('/', ''),
    scrollFlag = 0,
    scrollLinkSelector = '.anchor-scroll';

    -- add this condition.
    if(currentAnchor =='')
    {
     currentAnchor = '#initialized';
    }

You can simply check for empty values in you function setImmediateAnchor like below notice 3rd line and handle empty values.

   function setImmediateAnchor(anchorObject, time) {
    scrollFlag = 1;
    if (currentAnchor == '' || currentAnchor) {  -- THIS LINE
        $('html,body').stop().animate({
            'scrollTop': contentTop[anchorObject.attr('href')].top
        }, time, function() {
            $(scrollLinkSelector).parent().removeClass('active');
            anchorObject.parent().addClass('active');
            window.location.hash = '#/' + anchorObject.attr('href').substr(1);
            currentAnchor = anchorObject.attr('href');
            scrollFlag = 0;
        });
    }
}

Or you can use any other feasible way, the core problem lies in that condition that does not allow you to scroll since your variable is empty. You can fix either way which you find feasible.


问:
Cordova error - "npm does not support Node.js v0.12.9"
When I build my Cordova project in Visual Studio, it gives me an error "npm does not support Node.js v0.12.9" even though I have v6.10.3 installed. I tried the latest versions of npm, both x86 & x64.

It used to work, not sure what broke it.

答:
I looked through the build output again, and noticed that there were other errors too, although I can't remember what they were. It could be I had to increase the build output verbosity using Tools->Options->Projects and Solutions->Build and Run.

Looking at the xml in the .jsproj to see what the build process was doing, showed that it was running the C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE\Extensions\ApacheCordovaTools\Packages\vs-tac\install.js script. I put in console.log statements to see exactly what was happening, and somewhere along the way my error disappeared, not sure how.

So I can't give a precise answer, but this should help other users to debug their issues.


问:
VBA: Reverse an array?
How could I reverse an array that is full of integers e.g.:

```<code>[1;5;8;45;54]
</code>```

To:

```<code>[54;45;8;5;1]
</code>```

Are there any built in functions I could use?

I tried using this method:

```<code>Array.Reverse(arr)
</code>```

I added Mscorlib.dll from Tools > References, but it showed error: Syntax error. At the Array.Reverse(arr) location.

答:
Andre's answer referring to Chip Pearson's function I believe the +1 in the for loop is in error that in cases of LBound and UBound not BOTH being EVEN or BOTH being ODD results in the mid point reversal being reverted.  i.e. the difference between LBound and UBound being ODD.

Consider 0 = LBound and 9 = UBound.

9 + 1 = 10 / 2 = 5

So the loop will be for Ndx = 0 to 5.  That is 6 iterations.  One iteration too many.

Results in the following swaps.

Ndx = 0, Ndx2 = 9: 0<>9

Ndx = 1, Ndx2 = 8: 1<>8

Ndx = 2, Ndx2 = 7: 2<>7

Ndx = 3, Ndx2 = 6: 3<>6

Ndx = 4, Ndx2 = 5: 4<>5

Ndx = 5, Ndx2 = 4: 5<>4

So the mid point elements 4 and 5 are swapped, then swapped back.

Resulting in the order of: 9,8,7,6,4,5,3,2,1,0

Also LBound should be added to the UBound, not subtracted.  If subtracted then it only works for LBound of zero.  Consider 50 = LBound, 100 = UBound.  That would result in For Ndx = 50 to 25.  Note, this is supposed to be a FROM, TO calculation not an iterations count calculation.

Here is my functions for reversing one and two dimensional arrays.

They are also able to optionally retain a specified number of header rows.

```<code>' Reverse array (one dimensional), optionally retain header rows.
Private Sub Reverse_Array_1d(ByRef Ary As Variant, Optional Header_Rows As Integer = 0)

 Dim Dimension_Y As Integer     ' Rows (height)
 Dim Y_first As Long
 Dim Y_last As Long
 Dim Y_last_plus_Y_first As Long
 Dim Y_next As Long

 Dimension_Y = 1
 Y_first = LBound(Ary, Dimension_Y) + Header_Rows
 Y_last = UBound(Ary, Dimension_Y)
 Y_last_plus_Y_first = Y_last + Y_first

 Dim tmp As Variant

 For Y = Y_first To Y_last_plus_Y_first / 2
    Y_next = Y_last_plus_Y_first - Y
    tmp = Ary(Y_next)
    Ary(Y_next) = Ary(Y)
    Ary(Y) = tmp
 Next

End Sub

ReDim Ary(0 To 9) As Variant
Header_Rows = 1
Call Reverse_1d_Array(Ary, CInt(Header_Rows))
</code>```

```<code>' Reverse array (two dimensional), optionally retain header rows.
Private Sub Reverse_Array_2d(ByRef Ary As Variant, Optional Header_Rows As Integer = 0)

 Dim Dimension_Y As Integer     ' Rows (height)
 Dim Y_first As Long
 Dim Y_last As Long
 Dim Y_last_plus_Y_first As Long
 Dim Y_next As Long

 Dimension_Y = 1
 Y_first = LBound(Ary, Dimension_Y) + Header_Rows
 Y_last = UBound(Ary, Dimension_Y)
 Y_last_plus_Y_first = Y_last + Y_first

 Dim Dimension_X As Integer      ' Columns (width)
 Dim X_first As Long
 Dim X_last As Long

 Dimension_X = 2
 X_first = LBound(Ary, Dimension_X)
 X_last = UBound(Ary, Dimension_X)

 ReDim tmp(X_first To X_last) As Variant

 For Y = Y_first To Y_last_plus_Y_first / 2
    Y_next = Y_last_plus_Y_first - Y
    For X = X_first To X_last
        tmp(X) = Ary(Y_next, X)
        Ary(Y_next, X) = Ary(Y, X)
        Ary(Y, X) = tmp(X)
    Next
 Next

End Sub

ReDim Ary(0 To 9, 0 To 3) As Variant
Header_Rows = 1
Call Reverse_2d_Array(Ary, CInt(Header_Rows))
</code>```

Title: VBA: Reverse an array?

Body:
How could I reverse an array that is full of integers e.g.:

[1;5;8;45;54]

To:

[54;45;8;5;1]

Are there any built in functions I could use?

I tried using this method:

Array.Reverse(arr)

I added Mscorlib.dll from Tools > References, but it showed error: Syntax error. At the Array.Reverse(arr) location.

Body:
Andre's answer referring to Chip Pearson's function I believe the +1 in the for loop is in error that in cases of LBound and UBound not BOTH being EVEN or BOTH being ODD results in the mid point reversal being reverted.  i.e. the difference between LBound and UBound being ODD.

Consider 0 = LBound and 9 = UBound.

9 + 1 = 10 / 2 = 5

So the loop will be for Ndx = 0 to 5.  That is 6 iterations.  One iteration too many.

Results in the following swaps.

Ndx = 0, Ndx2 = 9: 0<>9

Ndx = 1, Ndx2 = 8: 1<>8

Ndx = 2, Ndx2 = 7: 2<>7

Ndx = 3, Ndx2 = 6: 3<>6

Ndx = 4, Ndx2 = 5: 4<>5

Ndx = 5, Ndx2 = 4: 5<>4

So the mid point elements 4 and 5 are swapped, then swapped back.

Resulting in the order of: 9,8,7,6,4,5,3,2,1,0

Also LBound should be added to the UBound, not subtracted.  If subtracted then it only works for LBound of zero.  Consider 50 = LBound, 100 = UBound.  That would result in For Ndx = 50 to 25.  Note, this is supposed to be a FROM, TO calculation not an iterations count calculation.

Here is my functions for reversing one and two dimensional arrays.

They are also able to optionally retain a specified number of header rows.

' Reverse array (one dimensional), optionally retain header rows.
Private Sub Reverse_Array_1d(ByRef Ary As Variant, Optional Header_Rows As Integer = 0)

 Dim Dimension_Y As Integer     ' Rows (height)
 Dim Y_first As Long
 Dim Y_last As Long
 Dim Y_last_plus_Y_first As Long
 Dim Y_next As Long

 Dimension_Y = 1
 Y_first = LBound(Ary, Dimension_Y) + Header_Rows
 Y_last = UBound(Ary, Dimension_Y)
 Y_last_plus_Y_first = Y_last + Y_first

 Dim tmp As Variant

 For Y = Y_first To Y_last_plus_Y_first / 2
    Y_next = Y_last_plus_Y_first - Y
    tmp = Ary(Y_next)
    Ary(Y_next) = Ary(Y)
    Ary(Y) = tmp
 Next

End Sub

ReDim Ary(0 To 9) As Variant
Header_Rows = 1
Call Reverse_1d_Array(Ary, CInt(Header_Rows))

' Reverse array (two dimensional), optionally retain header rows.
Private Sub Reverse_Array_2d(ByRef Ary As Variant, Optional Header_Rows As Integer = 0)

 Dim Dimension_Y As Integer     ' Rows (height)
 Dim Y_first As Long
 Dim Y_last As Long
 Dim Y_last_plus_Y_first As Long
 Dim Y_next As Long

 Dimension_Y = 1
 Y_first = LBound(Ary, Dimension_Y) + Header_Rows
 Y_last = UBound(Ary, Dimension_Y)
 Y_last_plus_Y_first = Y_last + Y_first

 Dim Dimension_X As Integer      ' Columns (width)
 Dim X_first As Long
 Dim X_last As Long

 Dimension_X = 2
 X_first = LBound(Ary, Dimension_X)
 X_last = UBound(Ary, Dimension_X)

 ReDim tmp(X_first To X_last) As Variant

 For Y = Y_first To Y_last_plus_Y_first / 2
    Y_next = Y_last_plus_Y_first - Y
    For X = X_first To X_last
        tmp(X) = Ary(Y_next, X)
        Ary(Y_next, X) = Ary(Y, X)
        Ary(Y, X) = tmp(X)
    Next
 Next

End Sub

ReDim Ary(0 To 9, 0 To 3) As Variant
Header_Rows = 1
Call Reverse_2d_Array(Ary, CInt(Header_Rows))


问:
Roulette wheel selection with positive and negative fitness values for minimization
I'm doing a genetic algorithm where each inidividual generates 3 new offsprings. The new individuals are evaluated using the fitness function, which may return negative and positive values. What is the correct approach to choose between the offsprings using the roulette wheel selection if I want to minimize?

Some possible values of the fitness function are: fitness_offspring_1 = -98.74; fitness_offspring_2 = -10.1; fitness_offspring_3 = 100.31

I'm working on Python but I only need the idea so I can implement it by myself.

答:
Roulette wheel selection is simply assigning probability values proportional to an individuals fitness. And then randomly selecting from that distribution. Fit individuals get a better chance at being selected, while less-fit individuals get lower chances.

You can easily adapt this to your code by using the offspring list instead of the individuals.

Lets start with as simple pseudo-codeish implementation in python, you can modify it to your needs:

```<code>fitness_sum = sum([ind.fitness for ind in individuals])
probability_offset = 0

for ind in individuals:
    ind.probability = probability_offset + (ind.fitness / fitness_sum)
    probability_offset += ind.probability

r = get_random_float()

selected_ind = individuals[0] # initialize
for ind in individuals:
    if ind.probability > r:
        break;
    selected_ind = ind
</code>```

Now, the code above (by the nature of roulette wheel) assumes all fitness values are positive. So in your case we need to normalize it. You can simply sum all values by the absolute value of smallest offspring. But that would make its probability 0 so you could simply add a bias to all to give it a slight chance as well.

Lets see how it works with simple values, say [1, 5, 14]

```<code>fitness_sum = 20
previous_probability = 0

# iterating first for loop:
individual[0].fitness => 0 + 1 / 20 = 0.05
individual[1].fitness => 0.05 + 5 / 20 = 0.3
individual[2].fitness => 0.3 + 14 / 20 = 1

# We created the wheel of probability distributions,
# 0 - 0.05 means we select individual 0
# 0.05 - 0.3 means we select individual 1 etc...

# say our random number r = 0.4

r = 0.4
selected_ind = individual_0

# iterating second for loop:
# 0.05 > 0.4 = false
selected_ind = individual_0
# 0.3 > 0.4 = false
selected_ind = individual_1
# 1.0 > 0.4 = true
break
</code>```

I'm sure there are much better pseudo-codes or implementations in python you can search for. Just wanted to give you an idea.

Body:
Roulette wheel selection is simply assigning probability values proportional to an individuals fitness. And then randomly selecting from that distribution. Fit individuals get a better chance at being selected, while less-fit individuals get lower chances.

You can easily adapt this to your code by using the offspring list instead of the individuals.

Lets start with as simple pseudo-codeish implementation in python, you can modify it to your needs:

fitness_sum = sum([ind.fitness for ind in individuals])
probability_offset = 0

for ind in individuals:
    ind.probability = probability_offset + (ind.fitness / fitness_sum)
    probability_offset += ind.probability

r = get_random_float()

selected_ind = individuals[0] # initialize
for ind in individuals:
    if ind.probability > r:
        break;
    selected_ind = ind

Now, the code above (by the nature of roulette wheel) assumes all fitness values are positive. So in your case we need to normalize it. You can simply sum all values by the absolute value of smallest offspring. But that would make its probability 0 so you could simply add a bias to all to give it a slight chance as well.

Lets see how it works with simple values, say [1, 5, 14]

fitness_sum = 20
previous_probability = 0

# iterating first for loop:
individual[0].fitness => 0 + 1 / 20 = 0.05
individual[1].fitness => 0.05 + 5 / 20 = 0.3
individual[2].fitness => 0.3 + 14 / 20 = 1

# We created the wheel of probability distributions,
# 0 - 0.05 means we select individual 0
# 0.05 - 0.3 means we select individual 1 etc...

# say our random number r = 0.4

r = 0.4
selected_ind = individual_0

# iterating second for loop:
# 0.05 > 0.4 = false
selected_ind = individual_0
# 0.3 > 0.4 = false
selected_ind = individual_1
# 1.0 > 0.4 = true
break

I'm sure there are much better pseudo-codes or implementations in python you can search for. Just wanted to give you an idea.


问:
Message: Set sys_temp_dir in your php.ini after installed composer
I've tried to install composer for my CodeIgniter project.

The installation was successful. But, when I type on command-line composer --version, it shows:

```<code>PHP temp directory (C:\Users\petik\AppData\Local\Temp) does not exist or is not writable to Composer. Set sys_temp_dir in your php.ini
Composer version 1.4.2 2017-05-17 08:17:52
</code>```

Can anyone help?

答: Change TEMP folder in php.ini. look for entry sys_temp_dir in your php.ini file and change the tmp location and set correct permissions.

Body:
I've tried to install composer for my CodeIgniter project.

The installation was successful. But, when I type on command-line composer --version, it shows:

PHP temp directory (C:\Users\petik\AppData\Local\Temp) does not exist or is not writable to Composer. Set sys_temp_dir in your php.ini
Composer version 1.4.2 2017-05-17 08:17:52

Can anyone help?


问:
Retrieve contents of a ZIP file on SharePoint without downloading it
I have written a bit of automated code that checks a SharePoint site and looks for a ZIP file (lets call it doc.zip).  If doc.zip is found, it downloads it, and then checks for a file (say target.docx).  doc.zip is about 300MB, and so I want to only download where necessary.

What I would like to know is that given SharePoint has some ZIP search capability, is it possible to write code using CSOM (c#) to find doc.zip, and then run some code to retrieve the contents of doc.zip without downloading it.

Just to re-iterate, I am comfortable with searching for files in a folder on SP, downloading the file, and unpacking zip entries.  What I need is to retrieve a ZIP files content on SP without downloading it.

E.g. is there a SP command:

```<code>cxt.Load(SomeZipFileQuery);
cxt.ExecuteQuery();
</code>```

Thanks in advance.

答: This capability is not available. I do like the idea. Having the ability to "parse" zip files on the server side and then download the relevant bits would be ideal. Perhaps raise this on uservoice to see if others also find this us https://sharepoint.uservoice.com</p>

ContentLicense: CC BY-SA 4.0

Body:
I have written a bit of automated code that checks a SharePoint site and looks for a ZIP file (lets call it doc.zip).  If doc.zip is found, it downloads it, and then checks for a file (say target.docx).  doc.zip is about 300MB, and so I want to only download where necessary.

What I would like to know is that given SharePoint has some ZIP search capability, is it possible to write code using CSOM (c#) to find doc.zip, and then run some code to retrieve the contents of doc.zip without downloading it.

Just to re-iterate, I am comfortable with searching for files in a folder on SP, downloading the file, and unpacking zip entries.  What I need is to retrieve a ZIP files content on SP without downloading it.

E.g. is there a SP command:

cxt.Load(SomeZipFileQuery);
cxt.ExecuteQuery();

Thanks in advance.


问:
Spring boot: Jersey ResourceConfig needs annotating?
I am just getting started with Spring Boot and I wanted to implement a ResourceConfig and I finding some conflicting ideas.

Take the following

```<code>@Component
public class JerseyExampleConfig extends ResourceConfig {
</code>```

The above is annotated with COMPONENT

```<code>@Configuration
public class JerseyExampleConfig extends ResourceConfig {
</code>```

Which one is correct?

I thought annotating with Configuration would be the correct way but it appears that the Component is used in examples.

Any ideas ?

Whats the difference?

答:
So even if you can not decide which to use for JerseyConfig you can determinate which is the better in a situation by reading what they actually mean:

@Configuration Indicates that a class declares one or more @Bean
  methods and may be processed by the Spring container to generate bean
  definitions and service requests for those beans at runtime

@Component Indicates that an annotated class is a "component". Such
  classes are considered as candidates for auto-detection when using
  annotation-based configuration and classpath scanning.

@Configuration is meta-annotated with @Component, therefore
  @Configuration classes are candidates for component scanning

So by the said above you can annotate your config class with @Configuration as well but it will be an unnecessary overhead.

Body:
I am just getting started with Spring Boot and I wanted to implement a ResourceConfig and I finding some conflicting ideas.

Take the following

@Component
public class JerseyExampleConfig extends ResourceConfig {

The above is annotated with COMPONENT

@Configuration
public class JerseyExampleConfig extends ResourceConfig {

Which one is correct?

I thought annotating with Configuration would be the correct way but it appears that the Component is used in examples.

Any ideas ?

Whats the difference?


问:
How to select top 1 and ordered by date in Oracle SQL?
There is a clear answer how to select top 1:

```<code>select * from table_name where rownum = 1
</code>```

and how to order by date in descending order:

```<code>select * from table_name order by trans_date desc
</code>```

but they does not work togeather (rownum is not generated according to trans_date):

```<code>... where rownum = 1 order by trans_date desc
</code>```

The question is how to select top 1 also ordered by date?

答:
```<code>... where rownum = 1 order by trans_date desc
</code>```

This selects one record arbitrarily chosen (where rownum = 1) and then sorts this one record (order by trans_date desc).

As shown by Ivan you can use a subquery where you order the records and then keep the first record with where rownum = 1in the outer query. This, however, is extremely Oracle-specific and violates the SQL standard where a subquery result is considered unordered (i.e. the order by clause can be ignored by the DBMS).

So better go with the standard solution. As of Oracle 12c:

```<code>select *
from table_name
order by trans_date desc
fetch first 1 row only;
</code>```

In older versions:

```<code>select *
from
(
  select t.*, row_number() over (order by trans_date desc) as rn
  from table_name t
)
where rn = 1;
</code>```

Body:
There is a clear answer how to select top 1:

select * from table_name where rownum = 1

and how to order by date in descending order:

select * from table_name order by trans_date desc

but they does not work togeather (rownum is not generated according to trans_date):

... where rownum = 1 order by trans_date desc

The question is how to select top 1 also ordered by date?

Body:
... where rownum = 1 order by trans_date desc

This selects one record arbitrarily chosen (where rownum = 1) and then sorts this one record (order by trans_date desc).

As shown by Ivan you can use a subquery where you order the records and then keep the first record with where rownum = 1in the outer query. This, however, is extremely Oracle-specific and violates the SQL standard where a subquery result is considered unordered (i.e. the order by clause can be ignored by the DBMS).

So better go with the standard solution. As of Oracle 12c:

select *
from table_name
order by trans_date desc
fetch first 1 row only;

In older versions:

select *
from
(
  select t.*, row_number() over (order by trans_date desc) as rn
  from table_name t
)
where rn = 1;


问:
Maven can't compile java 1.8
I'm trying to use maven to build a jar but I keep getting the error

```<code>ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile
(default-compile) on project Application: Fatal error compiling: invalid target release: 1.8 -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
</code>```

mvn -v outputs

```<code>mvn -version
Apache Maven 3.2.5 (12a6b3acb947671f09b81f49094c53f426d8cea1; 2014-12-14T09:29:23-08:00)
Maven home: /usr/local/Cellar/maven/3.2.5/libexec
Java version: 1.6.0_65, vendor: Apple Inc.
Java home: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Default locale: en_US, platform encoding: MacRoman
OS name: "mac os x", version: "10.10.1", arch: "x86_64", family: "mac"
</code>```

So it looks like its pointing to the 1.6jdk

but I have the 1.8 jdk

java -version

```<code>java -version
java version "1.8.0_25"
Java(TM) SE Runtime Environment (build 1.8.0_25-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)
</code>```

POM.xml

```<code> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.brian.ridecellchallenge</groupId>
    <artifactId>Application</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>1.6</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer
                                    implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.group.id.Launcher1</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>

    </build>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.6</version>
        </dependency>
    </dependencies>
</project>
</code>```

答:
Because Maven does not know version of jdk you want to build.
You can try with </p>

```<code><properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>
</code>```

Title: Maven can't compile java 1.8

Body:
I'm trying to use maven to build a jar but I keep getting the error

ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile
(default-compile) on project Application: Fatal error compiling: invalid target release: 1.8 -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException

mvn -v outputs

mvn -version
Apache Maven 3.2.5 (12a6b3acb947671f09b81f49094c53f426d8cea1; 2014-12-14T09:29:23-08:00)
Maven home: /usr/local/Cellar/maven/3.2.5/libexec
Java version: 1.6.0_65, vendor: Apple Inc.
Java home: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
Default locale: en_US, platform encoding: MacRoman
OS name: "mac os x", version: "10.10.1", arch: "x86_64", family: "mac"

So it looks like its pointing to the 1.6jdk

but I have the 1.8 jdk

java -version

java -version
java version "1.8.0_25"
Java(TM) SE Runtime Environment (build 1.8.0_25-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)

POM.xml

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.brian.ridecellchallenge</groupId>
    <artifactId>Application</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <build>
        <sourceDirectory>src</sourceDirectory>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>1.6</version>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer
                                    implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>com.group.id.Launcher1</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>

    </build>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>joda-time</groupId>
            <artifactId>joda-time</artifactId>
            <version>2.6</version>
        </dependency>
    </dependencies>
</project>

Body:
Because Maven does not know version of jdk you want to build.
You can try with

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>


问:
In Django, how to clear all the memcached keys and values?
I don't want to restart the memcached server!</p>

答:
And an one-liner from console:</p>

```<code>echo "from django.core.cache import cache; cache._cache.flush_all()" | ./manage.py shell [--settings=myapp.settings_live]
</code>```

Body:
And an one-liner from console:

echo "from django.core.cache import cache; cache._cache.flush_all()" | ./manage.py shell [--settings=myapp.settings_live]


问:
Add entries to array under specific key
I am looping through a set of trips, and every trip has a End-Station. It is possible to select a broad date range, such that there are multiple trips for the same End-Station. My goal is to add trips from another "date" to an array which already has an entry for a End-Station.

```<code>if(typeof(theResponse[current]) !== 'undefined') {
    for(var i=0; i < theResponse[current].length; i++) {

        var station = theResponse[current][i];
        Trips.push({
            EndStation: station.EndStationID, // Is the same for any theResponse[current][i]
            TripsOut: station.Tripcount,      // This should be added under the same "EndStation"
            Enabled: true,
            Trips: station.Trips
    })
    }
} else {
    console.log("sorry, no trips.");
}
</code>```

For example: TripsOut might be 5 for theResponse[current][1] for a particular End-Station, and then it is 6 for theResponse[current][2] for that same End-Station. How can I add these two such that there is a single entry (in this case 11) under the specific station? Currently, it creates another entry, so there are multiple entries for the same End-Station.

答:
I followed above advice and check if the "End-Station" already exists in the array, then update accordingly:</p>

```<code>var station = theResponse[current][i];
var index = Trips.findIndex(x => x.EndStation == station.EndStation);
if(index !== -1) {
    Trips[index].TripsOut = Trips[index].TripsOut + station.Tripcount; // Add to existing value
    Trips[index].Trips.push(station.Trips); // Is an array, so push to append
} else {
    tripDetails.push({
        EndStation: station.EndStation,
        TripsOut: station.Tripcount,
        Enabled: true,
        Trips: station.Trips
    })
}
</code>```

Title: Add entries to array under specific key

Body:
I am looping through a set of trips, and every trip has a End-Station. It is possible to select a broad date range, such that there are multiple trips for the same End-Station. My goal is to add trips from another "date" to an array which already has an entry for a End-Station.

if(typeof(theResponse[current]) !== 'undefined') {
    for(var i=0; i < theResponse[current].length; i++) {

        var station = theResponse[current][i];
        Trips.push({
            EndStation: station.EndStationID, // Is the same for any theResponse[current][i]
            TripsOut: station.Tripcount,      // This should be added under the same "EndStation"
            Enabled: true,
            Trips: station.Trips
    })
    }
} else {
    console.log("sorry, no trips.");
}

For example: TripsOut might be 5 for theResponse[current][1] for a particular End-Station, and then it is 6 for theResponse[current][2] for that same End-Station. How can I add these two such that there is a single entry (in this case 11) under the specific station? Currently, it creates another entry, so there are multiple entries for the same End-Station.

Body:
I followed above advice and check if the "End-Station" already exists in the array, then update accordingly:

var station = theResponse[current][i];
var index = Trips.findIndex(x => x.EndStation == station.EndStation);
if(index !== -1) {
    Trips[index].TripsOut = Trips[index].TripsOut + station.Tripcount; // Add to existing value
    Trips[index].Trips.push(station.Trips); // Is an array, so push to append
} else {
    tripDetails.push({
        EndStation: station.EndStation,
        TripsOut: station.Tripcount,
        Enabled: true,
        Trips: station.Trips
    })
}


问:
Javascript: nice human readable join of list
Having a list (array) of tags ['tag1', 'tag2', 'tag3'] I want to generate a nice title like: Content tagged tag1, tag2 and tag3.

For the moment I have:

```<code>"Content tagged " + tags_titles.join(" and ");
</code>```

with the result:
Content tagged tag1 and tag2 and tag3

I know it's a simple question, but I am curious if there is a nice solution for this case.

答:
Try like this</p>

```<code>var g = ['tag1', 'tag2', 'tag3'];
var title = g.slice(0, g.length-1).join(',').concat(' and ').concat(g[g.length-1]);
</code>```

Body:
Having a list (array) of tags ['tag1', 'tag2', 'tag3'] I want to generate a nice title like: Content tagged tag1, tag2 and tag3.

For the moment I have:

"Content tagged " + tags_titles.join(" and ");

with the result:
Content tagged tag1 and tag2 and tag3

I know it's a simple question, but I am curious if there is a nice solution for this case.

Body:
Try like this

var g = ['tag1', 'tag2', 'tag3'];
var title = g.slice(0, g.length-1).join(',').concat(' and ').concat(g[g.length-1]);


问:
How to redirect subdomain to main domain maintaining the same URL?
My main domain(www.mysite.com) is pointing to a folder in my server (/home/user_name/htdocs/mysite.com).

I have recently created a subdomain(m.mysite.com) through my hosting account. But it is pointing it to a new folder (/home/user_name/htdocs/m.mysite.com) in my server. I am not able to edit the path to which this new subdomain points to. All my files are hosted in my main folder path.

My Requirement -

When a user visits m.mysite.com he should be redirected to mysite.com but the URL in the browser should still say m.mysite.com

I'm handling the mobile view by detecting the subdomain using $_SERVER['SERVER_NAME']

答:
I think you should able to write an .htaccess file with this rule, provided it is the same user and has read permisssions to both URLs:

```<code>RewriteEngine on
RewriteCond %{HTTP_HOST} ^m\.mysite\.com
RewriteRule (.*) ../mysite.com/$1 [L]
</code>```

Or, you can make a symlink to the main site, let's say:

```<code>./mysite.com
    dirs and folders

./m.mysite.com
    drwxr-xr-x main_site -> ../mysite.com
</code>```

And an htaccess:

```<code>Options +FollowSymLinks
RewriteEngine On
RewriteRule ^/?mysite\.com 404.html [L] # Do not show the real filesystem layer
RewriteRule (.*) ./mysite.com/$1 [L]
</code>```

Body:
I think you should able to write an .htaccess file with this rule, provided it is the same user and has read permisssions to both URLs:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^m\.mysite\.com
RewriteRule (.*) ../mysite.com/$1 [L]

Or, you can make a symlink to the main site, let's say:

./mysite.com
    dirs and folders

./m.mysite.com
    drwxr-xr-x main_site -> ../mysite.com

And an htaccess:

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^/?mysite\.com 404.html [L] # Do not show the real filesystem layer
RewriteRule (.*) ./mysite.com/$1 [L]


问:
selenium web driver : Able to open Firefox browser but The address isn’t valid
```<code>     WebDriver driver = new FirefoxDriver();

    driver.navigate().to("https://www.google.com");
</code>```

Says "Invalid address"

```<code>public static void main(String[] args) {
        // TODO Auto-generated method stub

        driver.navigate().to("https://www.google.com");
</code>```

答:
Replace , </p>

```<code>driver.navigate().to("https://www.google.com");
</code>```

<p>with </p>

```<code>driver.get("https://www.google.com");
</code>```

Body:
     WebDriver driver = new FirefoxDriver();

    driver.navigate().to("https://www.google.com");

Says "Invalid address"

public static void main(String[] args) {
        // TODO Auto-generated method stub

        driver.navigate().to("https://www.google.com");

Body:
Replace ,

driver.navigate().to("https://www.google.com");

with

driver.get("https://www.google.com");


问:
Swift iOS- How to Add Button to the outside a CollectionView Cell

I want to get a deleteButton that is a delete image to sit on the outside of a collectionViewCell (it can be partially inside).

I looked at other SO answers and they said just play with the button's frame's Rect's x & y values which I did. When I set the x & y values to 0,0 I get:

```<code> class CustomCell: UICollectionViewCell {

 @IBOutlet weak var imageView: UIImageView!
 var deleteButton: UIButton!
 var deleteButtonImg: UIImage!

 override func awakeFromNib() {
     super.awakeFromNib()

 deleteButton = UIButton(frame: CGRect(x: 0, y: 0, width: frame.size.width/4, height: frame.size.width/4))

 deleteButtonImg = UIImage(named: "delete-icon")!.withRenderingMode(.alwaysTemplate)
 deleteButton.setImage(deleteButtonImg, for: .normal)
 deleteButton.tintColor = UIColor.red

 contentView.addSubview(deleteButton)
 }
</code>```

When I try to set the the Rect's x & y to -10,-10 the deleteButton gets clipped inside the cell's imageView. I don't have clipsToBounds set.

```<code> deleteButton = UIButton(frame: CGRect(x: -10, y: -10, width: frame.size.width/4, height: frame.size.width/4))
</code>```

I even tried setting clipToBounds to false but I get the same effect as pic # 3.

```<code>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell

        cell.imageView.image = myImageArray[indexPath.row]
        cell.imageView.clipsToBounds = false

        return cell
    }
</code>```

Where am I going wrong?

答:
The problem was inside storyboard I had a:

```<code>CollectionView
      -CustomCell (type collectionViewCell)
           -imageView
</code>```

Under the Attributes Inspector, in the Drawing section, all 3 of these have the property clipsToBounds.

I overlooked the fact that I had clipsToBounds set to false (unchecked) on the imageView but set to true (checked) on the CustomCell and the CollectionView.

If anyone else has this problem make sure you uncheck clipsToBounds on the collectionView, collectionViewCell, and the imageView.

Body:
I want to get a deleteButton that is a delete image to sit on the outside of a collectionViewCell (it can be partially inside).

I looked at other SO answers and they said just play with the button's frame's Rect's x & y values which I did. When I set the x & y values to 0,0 I get:

 class CustomCell: UICollectionViewCell {

 @IBOutlet weak var imageView: UIImageView!
 var deleteButton: UIButton!
 var deleteButtonImg: UIImage!

 override func awakeFromNib() {
     super.awakeFromNib()

 deleteButton = UIButton(frame: CGRect(x: 0, y: 0, width: frame.size.width/4, height: frame.size.width/4))

 deleteButtonImg = UIImage(named: "delete-icon")!.withRenderingMode(.alwaysTemplate)
 deleteButton.setImage(deleteButtonImg, for: .normal)
 deleteButton.tintColor = UIColor.red

 contentView.addSubview(deleteButton)
 }

When I try to set the the Rect's x & y to -10,-10 the deleteButton gets clipped inside the cell's imageView. I don't have clipsToBounds set.

 deleteButton = UIButton(frame: CGRect(x: -10, y: -10, width: frame.size.width/4, height: frame.size.width/4))

I even tried setting clipToBounds to false but I get the same effect as pic # 3.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CustomCell", for: indexPath) as! CustomCell

        cell.imageView.image = myImageArray[indexPath.row]
        cell.imageView.clipsToBounds = false

        return cell
    }

Where am I going wrong?

Body:
The problem was inside storyboard I had a:

CollectionView
      -CustomCell (type collectionViewCell)
           -imageView

Under the Attributes Inspector, in the Drawing section, all 3 of these have the property clipsToBounds.

I overlooked the fact that I had clipsToBounds set to false (unchecked) on the imageView but set to true (checked) on the CustomCell and the CollectionView.

If anyone else has this problem make sure you uncheck clipsToBounds on the collectionView, collectionViewCell, and the imageView.


答:
A bit of slicing and dicing using Array.prototype.slice:

function naturalLanguageJoin(arr){
    if(!arr)
       return '';
    if(arr.length<2)
       return (arr.length>0) ? arr[0] : '';
    return arr.slice(0,arr.length-1).join(", ") + " and " + arr[arr.length-1];
}

console.log(naturalLanguageJoin(['tag1', 'tag2', 'tag3']));
console.log(naturalLanguageJoin(['tag1', 'tag2']));
console.log(naturalLanguageJoin(['tag1']));
console.log(naturalLanguageJoin([]));
console.log(naturalLanguageJoin(null));```

Title: Javascript: nice human readable join of list


问:
Import a Null value into Acumatica
I am trying to import an Null value into Acumatica.  Specifically I am trying to remove the GL Expense Account on a number of Vendor Records.
I have tried, ='', ="", =" ",=' ',=NULL,NULL,='NULL', in the Value field of the import scenario.  I am working with an Excel data source by I have also tried, CSV and hard coding the value in the integration.

None of which see to work.

答: In acumatica version before 6.1 Update 5 you cannot do what you want. In versions 6.1 update 5 and bigger, you can set in import scenario formula '=Null' for field and this field will be nullified.

Title: Import a Null value into Acumatica


答:
An array can be treated as a stack so you can pop the last element and in turn write this

```<code>var last = tags_titles.pop();
last = tags_titles.length ? ` and ${last}` : last;
`Content tagged ${tags_titles.join(", ")} ${last}`
</code>```

The code uses ES6 string templates, which I generally find to be more readable than doing string concatenation in the code. It also utilizes the fact that the pop method essentially performs to operations. Gets the lasst element of the array and mutate the array. That eliminate the need to do the mutation explicitly (using slice)

Body:
An array can be treated as a stack so you can pop the last element and in turn write this

var last = tags_titles.pop();
last = tags_titles.length ? ` and ${last}` : last;
`Content tagged ${tags_titles.join(", ")} ${last}`

The code uses ES6 string templates, which I generally find to be more readable than doing string concatenation in the code. It also utilizes the fact that the pop method essentially performs to operations. Gets the lasst element of the array and mutate the array. That eliminate the need to do the mutation explicitly (using slice)


答:
Something like this would be my approach

function arrayFormat(arr) {
    var output = arr.splice(0, arr.length - 1).join(", ");
    output += " and " + arr[0];
    return output;
}
console.log(arrayFormat(["a", "b", "c"]));```


问:
Session from javascript
I'd like to inspect the session variable.  Best case something that works in the firebugs little interpreter, but if I have to put it in the file thats fine.  Right now I just made a short PHP to output $_SESSION, but if I could find something analogous to be done right in the browser that would be ideal.  document.cookie doesn't seem to do what im looking for, at least not that i see.

Basically looking for something analogous to $_SESSION that I can use in javascript

EDIT - was trying to see if i could get anything more than, or extract the meaning  PHPSESSID=o147cf52u9d7qr251hc3n6ilu2; ASESSIONID=101wvpe-3FA77F204CFF55BA61E696AD3F62F0F8 on the client-side.   As it stands I guess i can just write a small ajax function to a url that echos the session.  Thanks for the help!

PS - Do those document.cookie values have anything to do with whats inside the session, or are they just identifiers to tell one session from another?

答: You can't access PHP sessions within JavaScript directly.  You could however make an Ajax call to a PHP script which will return the PHP sessions.  This is your best option.</p>

Title: Session from javascript


问:
Angular2 can't see images after using ng build --prod
I upload my angular2 project to my webhost, but for some reason i can't see images on my website. Rest of the website works fine. The dist folder that comes after using ng build --prod does not contain my image folder that was in src/app/images location.  </p>

答:
copy images folder to assets, or link as asset in .angular-cli.json file.

If you copy to assets your path will be

For 2nd option, you can refer this document: https://github.com/angular/angular-cli/wiki/stories-asset-configuration

Body:
copy images folder to assets, or link as asset in .angular-cli.json file.

If you copy to assets your path will be <img src="assets/images/path-to-abc.png">

For 2nd option, you can refer this document: https://github.com/angular/angular-cli/wiki/stories-asset-configuration