问:
Merge two arrays and sort the final one
In an interview I was asked the following question.
I am given two arrays, both of them are sorted.

BUT

Array 1 will have few -1's and Array 2 will have total numbers as the total number of -1's in Array 1.

So in the below example
array1 has three -1's hence array2 has 3 numbers.

let say

```<code>var arrayOne = [3,6,-1,11,15,-1,23,34,-1,42];
var arrayTwo = [1,9,28];
</code>```

Both of the arrays will be sorted.

Now I have to write a program that will merge arrayTwo in arrayOne by replacing -1's, and arrayOne should be in sorted order.

So the output will be

```<code>arrayOne = [ 1,3, 6, 9, 11, 15, 23, 28 ,34, 42 ]
</code>```

Sorting should be done without use of any sort API.

I have written a following code

function puzzle01() {
  var arrayOne = [3, 6, -1, 11, 15, -1, 23, 34, -1, 42];
  var arrayTwo = [1, 9, 28];
  var array1Counter = 0,
    isMerged = false;

  console.log(" array-1 ", arrayOne);
  console.log(" array-2 ", arrayTwo);

  for (var array2Counter = 0; array2Counter < arrayTwo.length; array2Counter++) {
    isMerged = false;
    while (isMerged === false && array1Counter < arrayOne.length) {

      if (arrayOne[array1Counter] === -1) {
        arrayOne[array1Counter] = arrayTwo[array2Counter];
        isMerged = true;
      }

      array1Counter++;
    }
  } //for

  console.log(" array-1 + array-2 ", arrayOne);
  bubbleSort(arrayOne);
  console.log(" Sorted array ", arrayOne);
} //puzzle01

puzzle01();

// implementation of bubble sort for sorting the
// merged array
function bubbleSort(arrayOne) {
  var nextPointer = 0,
    temp = 0,
    hasSwapped = false;

  do {
    hasSwapped = false;
    for (var x = 0; x < arrayOne.length; x++) {
      nextPointer = x + 1;
      if (nextPointer < arrayOne.length && arrayOne[x] > arrayOne[nextPointer]) {
        temp = arrayOne[x];
        arrayOne[x] = arrayOne[nextPointer];
        arrayOne[nextPointer] = temp;
        hasSwapped = true;
      }
    } //for
  } while (hasSwapped === true);
} // bubbleSort```
</div>
</div>
</p>

<p>The output of the above code is </p>

``` array-1  [ 3, 6, -1, 11, 15, -1, 23, 34, -1, 42 ]
 array-2  [ 1, 9, 28 ]
 array-1 + array-2  [ 3, 6, 1, 11, 15, 9, 23, 34, 28, 42 ]
 Sorted array  [ 1, 3, 6, 9, 11, 15, 23, 28, 34, 42 ]
```

<p>From the above code you can see, I have first merged the two arrays and than sorted the final one.</p>

<p>Just wanted to know,
Is there a better solution.</p>

<p>Is there any flaw in my solution.</p>

<p>Please let me know, it will be helpfull.   </p>

<p>After reading all your very helpful comments and answers, I found was able to figure out a more faster solution.</p>

<p>Let us take an example </p>

```var arrayOne = [3,6,-1,11,15,-1,32,34,-1,42,-1];
var arrayTwo = [1,10,17,56],
```

<p>Step1: I will iterate through arrayTwo. Take the next element (i.e. '1') and compare with next element of arrayOne (i.e. '3') and compare. </p>

<p>step 2a : If element of array1 is greater than element of array2 than swap array elements. Now go to next element of array1. </p>

<p>OR</p>

<p>step 2b : If element of array1 is equal to -1 than swap array elements. Now go to next element of array2. </p>

<p>step 3: Go to step 1.</p>

<p>So </p>

<p>in the above example</p>

<p>first iteration,
    array1 = [1,6,-1,11,...]
    array2 = [3,10,17,56]</p>

<p>second iteration,
    array1 = [1,3,-1,11,..]
    array2 = [6,10,17,56]</p>

<p>third iteration,
    array1 = [1,3,6,11..]
    array2 = [-1,10,17,56]</p>

<p>fourth iteration
    array1 = [1,3,6,10,..]
    array2 = [-1,11,17,56]</p>

<p>and so on.</p>

<p>at the end I will get the output</p>

```array1 = [ 1, 3, 6, 10, 11, 15, 17, 32, 34, 42, 56 ]
array2 = [-1,-1,-1]
```

<p>Please find the code below,</p>

```function puzzle02(arrayOne,arrayTwo){
    var array1Counter = 0,
        array2Counter = 0,
        hasMinusOneOccurred = false;

    console.log(" array-1 ",arrayOne);
    console.log(" array-2 ",arrayTwo);

    while(array2Counter < arrayTwo.length){ // iterate through array2

        do{
            if(arrayOne[array1Counter] === -1){ // if -1 occurred in array1
                hasMinusOneOccurred = true;

                // swaping numbers at current position of array1
                // with current position of array2
                swap(arrayOne,arrayTwo,array1Counter,array2Counter);

                // recheck if the current value is greater than other values
                // of array1
                if(recheckAndSort(arrayOne,array1Counter) === true){
                    array1Counter = -1;// recheck array1 from start
                }else{
                    // recheck the current array1 counter, for doing so go 1 count back
                    // so that even if the counter is incremented it points to current
                    // number itself
                    array1Counter--;
                }

            }else if(arrayOne[array1Counter] > arrayTwo[array2Counter]){
                swap(arrayOne,arrayTwo,array1Counter,array2Counter);
            }else{
                array1Counter++;
                continue;
            }

            array1Counter++;
        }while(hasMinusOneOccurred === false); // end of do-while

        array2Counter++;
        hasMinusOneOccurred = false;

    }//end of while

    console.log(" Sorted array ",arrayOne);

    function swap(arr1,arr2,arr1Index,arr2Index){
        var temp = arr2[arr2Index];
        arr2[arr2Index] = arr1[arr1Index];
        arr1[arr1Index] = temp;
    }// end of swap

    // this method is call if -1 occures in array1
    function recheckAndSort(arrayOne,array1Counter){
        var isGreaterVal = true,
            prevCounter = 0,
            nextCounter = 0,
            temp = 0,
            recheckFromStart = false;

        if(array1Counter === 0){ // if -1 occurred at first position of array1.

            // flag to check if -1 occurrec at first position
            // if yes, iterate array1 from start
            recheckFromStart = true;

            // iterate forward to check wether any numbers are less than current position,
            // if yes than move forward
            for(var j = 0; isGreaterVal; j++){
                nextCounter = j + 1;

                if(arrayOne[nextCounter] === -1){
                    // swaping numbers of array1 between next to current
                    swap(arrayOne,arrayOne,nextCounter,j);
                    isGreaterVal = true;

                }else if(arrayOne[nextCounter] < arrayOne[j]){
                    // swaping numbers of array1 between next to current
                    swap(arrayOne,arrayOne,nextCounter,j);
                    isGreaterVal = true;

                }else{
                    isGreaterVal = false;
                }

             }//end of for

         }else{// if -1 occurred in the middle position of array1 and is been swaped then
            // iterate backwards to check if any number less then current position exists,
            // if yes than shift backwards.
            for(var i = array1Counter; isGreaterVal; i--){
                prevCounter = i - 1;

                if(arrayOne[prevCounter] > arrayOne[i]){

                    // swaping numbers of array1 between previous to current
                    swap(arrayOne,arrayOne,prevCounter,i);
                    isGreaterVal = true;
                }else{
                    isGreaterVal = false;
                }

            }// end of for
        }

        return recheckFromStart;
    }// end of recheckAndSort
} // end of puzzle02
```

<p>After calling the above function</p>

```puzzle02([3,6,-1,11,15,-1,32,34,-1,42,-1],[1,10,17,56]);
```

<p>The output of above code is,</p>

``` array-1  [ 3, 6, -1, 11, 15, -1, 32, 34, -1, 42, -1 ]
 array-2  [ 1, 10, 17, 56 ]
 Sorted array  [ 1, 3, 6, 10, 11, 15, 17, 32, 34, 42, 56 ]
```

Thanks.

答:
Let me re-phrase three most important aspects of the task:

Both arrays are sorted and include positive integers (except -1 place-holders in Array1)

The -1 is meaningless placeholder (its position in Array1 is random)

Array1 length equals output array length

Pseudo logic:

parse both array1 and array2 from the first position to end of array

ignore -1 values in array1

if array1[current position] <= array2[current position] then write array1[current position] into merged array and move to next position in array1; otherwise apply same for array2

Code example:

```<code>            public static void AMerge()
        {
            int[] array1 = new int[] { 3, 6, -1, 11, 15, -1, 23, 34, -1, 42 };
            int[] array2 = new int[] { 1, 9, 28 };
            int[] arrayMerged = new int[array1.Length];

            int array1Index = 0;
            int array2Index = 0;

            for (int arrayMergedIndex = 0; arrayMergedIndex < array1.Length; arrayMergedIndex++)
            {
                while (array1[array1Index] == -1) array1Index++; //ignore -1 placeholders
                if ((array1Index < array1.Length && array2Index >= array2.Length)
                    || array1[array1Index] <= array2[array2Index])  //choose which array will provide current merged value
                {
                    arrayMerged[arrayMergedIndex] = array1[array1Index];
                    array1Index++;
                }
                else
                {
                    arrayMerged[arrayMergedIndex] = array2[array2Index];
                    array2Index++;
                }
            }

            char[] charsToTrim = { ',', ' '};
            string arrayMergedString = "{";
            foreach (int f in arrayMerged) arrayMergedString += f.ToString() + " ";
            arrayMergedString = arrayMergedString.TrimEnd(charsToTrim) + "}";
            Console.WriteLine(arrayMergedString);
            Console.ReadKey();
        }
    }
</code>```

Note:

Optimizing for speed => creating new arrayMerged; optimization for space would require moving array1 elements in the else branch

Title: Merge two arrays and sort the final one

Body:
In an interview I was asked the following question.
I am given two arrays, both of them are sorted.

BUT

Array 1 will have few -1's and Array 2 will have total numbers as the total number of -1's in Array 1.

So in the below example
array1 has three -1's hence array2 has 3 numbers.

let say

var arrayOne = [3,6,-1,11,15,-1,23,34,-1,42];
var arrayTwo = [1,9,28];

Both of the arrays will be sorted.

Now I have to write a program that will merge arrayTwo in arrayOne by replacing -1's, and arrayOne should be in sorted order.

So the output will be

arrayOne = [ 1,3, 6, 9, 11, 15, 23, 28 ,34, 42 ]

Sorting should be done without use of any sort API.

I have written a following code

function puzzle01() {
  var arrayOne = [3, 6, -1, 11, 15, -1, 23, 34, -1, 42];
  var arrayTwo = [1, 9, 28];
  var array1Counter = 0,
    isMerged = false;

  console.log(" array-1 ", arrayOne);
  console.log(" array-2 ", arrayTwo);

  for (var array2Counter = 0; array2Counter < arrayTwo.length; array2Counter++) {
    isMerged = false;
    while (isMerged === false && array1Counter < arrayOne.length) {

      if (arrayOne[array1Counter] === -1) {
        arrayOne[array1Counter] = arrayTwo[array2Counter];
        isMerged = true;
      }

      array1Counter++;
    }
  } //for

  console.log(" array-1 + array-2 ", arrayOne);
  bubbleSort(arrayOne);
  console.log(" Sorted array ", arrayOne);
} //puzzle01

puzzle01();

// implementation of bubble sort for sorting the
// merged array
function bubbleSort(arrayOne) {
  var nextPointer = 0,
    temp = 0,
    hasSwapped = false;

  do {
    hasSwapped = false;
    for (var x = 0; x < arrayOne.length; x++) {
      nextPointer = x + 1;
      if (nextPointer < arrayOne.length && arrayOne[x] > arrayOne[nextPointer]) {
        temp = arrayOne[x];
        arrayOne[x] = arrayOne[nextPointer];
        arrayOne[nextPointer] = temp;
        hasSwapped = true;
      }
    } //for
  } while (hasSwapped === true);
} // bubbleSort

The output of the above code is

 array-1  [ 3, 6, -1, 11, 15, -1, 23, 34, -1, 42 ]
 array-2  [ 1, 9, 28 ]
 array-1 + array-2  [ 3, 6, 1, 11, 15, 9, 23, 34, 28, 42 ]
 Sorted array  [ 1, 3, 6, 9, 11, 15, 23, 28, 34, 42 ]

From the above code you can see, I have first merged the two arrays and than sorted the final one.

Just wanted to know,
Is there a better solution.

Is there any flaw in my solution.

Please let me know, it will be helpfull.

After reading all your very helpful comments and answers, I found was able to figure out a more faster solution.

Let us take an example

var arrayOne = [3,6,-1,11,15,-1,32,34,-1,42,-1];
var arrayTwo = [1,10,17,56],

Step1: I will iterate through arrayTwo. Take the next element (i.e. '1') and compare with next element of arrayOne (i.e. '3') and compare.

step 2a : If element of array1 is greater than element of array2 than swap array elements. Now go to next element of array1.

OR

step 2b : If element of array1 is equal to -1 than swap array elements. Now go to next element of array2.

step 3: Go to step 1.

So

in the above example

first iteration,
    array1 = [1,6,-1,11,...]
    array2 = [3,10,17,56]

second iteration,
    array1 = [1,3,-1,11,..]
    array2 = [6,10,17,56]

third iteration,
    array1 = [1,3,6,11..]
    array2 = [-1,10,17,56]

fourth iteration
    array1 = [1,3,6,10,..]
    array2 = [-1,11,17,56]

and so on.

at the end I will get the output

array1 = [ 1, 3, 6, 10, 11, 15, 17, 32, 34, 42, 56 ]
array2 = [-1,-1,-1]

Please find the code below,

function puzzle02(arrayOne,arrayTwo){
    var array1Counter = 0,
        array2Counter = 0,
        hasMinusOneOccurred = false;

    console.log(" array-1 ",arrayOne);
    console.log(" array-2 ",arrayTwo);

    while(array2Counter < arrayTwo.length){ // iterate through array2

        do{
            if(arrayOne[array1Counter] === -1){ // if -1 occurred in array1
                hasMinusOneOccurred = true;

                // swaping numbers at current position of array1
                // with current position of array2
                swap(arrayOne,arrayTwo,array1Counter,array2Counter);

                // recheck if the current value is greater than other values
                // of array1
                if(recheckAndSort(arrayOne,array1Counter) === true){
                    array1Counter = -1;// recheck array1 from start
                }else{
                    // recheck the current array1 counter, for doing so go 1 count back
                    // so that even if the counter is incremented it points to current
                    // number itself
                    array1Counter--;
                }

            }else if(arrayOne[array1Counter] > arrayTwo[array2Counter]){
                swap(arrayOne,arrayTwo,array1Counter,array2Counter);
            }else{
                array1Counter++;
                continue;
            }

            array1Counter++;
        }while(hasMinusOneOccurred === false); // end of do-while

        array2Counter++;
        hasMinusOneOccurred = false;

    }//end of while

    console.log(" Sorted array ",arrayOne);

    function swap(arr1,arr2,arr1Index,arr2Index){
        var temp = arr2[arr2Index];
        arr2[arr2Index] = arr1[arr1Index];
        arr1[arr1Index] = temp;
    }// end of swap

    // this method is call if -1 occures in array1
    function recheckAndSort(arrayOne,array1Counter){
        var isGreaterVal = true,
            prevCounter = 0,
            nextCounter = 0,
            temp = 0,
            recheckFromStart = false;

        if(array1Counter === 0){ // if -1 occurred at first position of array1.

            // flag to check if -1 occurrec at first position
            // if yes, iterate array1 from start
            recheckFromStart = true;

            // iterate forward to check wether any numbers are less than current position,
            // if yes than move forward
            for(var j = 0; isGreaterVal; j++){
                nextCounter = j + 1;

                if(arrayOne[nextCounter] === -1){
                    // swaping numbers of array1 between next to current
                    swap(arrayOne,arrayOne,nextCounter,j);
                    isGreaterVal = true;

                }else if(arrayOne[nextCounter] < arrayOne[j]){
                    // swaping numbers of array1 between next to current
                    swap(arrayOne,arrayOne,nextCounter,j);
                    isGreaterVal = true;

                }else{
                    isGreaterVal = false;
                }

             }//end of for

         }else{// if -1 occurred in the middle position of array1 and is been swaped then
            // iterate backwards to check if any number less then current position exists,
            // if yes than shift backwards.
            for(var i = array1Counter; isGreaterVal; i--){
                prevCounter = i - 1;

                if(arrayOne[prevCounter] > arrayOne[i]){

                    // swaping numbers of array1 between previous to current
                    swap(arrayOne,arrayOne,prevCounter,i);
                    isGreaterVal = true;
                }else{
                    isGreaterVal = false;
                }

            }// end of for
        }

        return recheckFromStart;
    }// end of recheckAndSort
} // end of puzzle02

After calling the above function

puzzle02([3,6,-1,11,15,-1,32,34,-1,42,-1],[1,10,17,56]);

The output of above code is,

 array-1  [ 3, 6, -1, 11, 15, -1, 32, 34, -1, 42, -1 ]
 array-2  [ 1, 10, 17, 56 ]
 Sorted array  [ 1, 3, 6, 10, 11, 15, 17, 32, 34, 42, 56 ]

Thanks.

Body:
Let me re-phrase three most important aspects of the task:

Both arrays are sorted and include positive integers (except -1 place-holders in Array1)

The -1 is meaningless placeholder (its position in Array1 is random)

Array1 length equals output array length

Pseudo logic:

parse both array1 and array2 from the first position to end of array

ignore -1 values in array1

if array1[current position] <= array2[current position] then write array1[current position] into merged array and move to next position in array1; otherwise apply same for array2

Code example:

            public static void AMerge()
        {
            int[] array1 = new int[] { 3, 6, -1, 11, 15, -1, 23, 34, -1, 42 };
            int[] array2 = new int[] { 1, 9, 28 };
            int[] arrayMerged = new int[array1.Length];

            int array1Index = 0;
            int array2Index = 0;

            for (int arrayMergedIndex = 0; arrayMergedIndex < array1.Length; arrayMergedIndex++)
            {
                while (array1[array1Index] == -1) array1Index++; //ignore -1 placeholders
                if ((array1Index < array1.Length && array2Index >= array2.Length)
                    || array1[array1Index] <= array2[array2Index])  //choose which array will provide current merged value
                {
                    arrayMerged[arrayMergedIndex] = array1[array1Index];
                    array1Index++;
                }
                else
                {
                    arrayMerged[arrayMergedIndex] = array2[array2Index];
                    array2Index++;
                }
            }

            char[] charsToTrim = { ',', ' '};
            string arrayMergedString = "{";
            foreach (int f in arrayMerged) arrayMergedString += f.ToString() + " ";
            arrayMergedString = arrayMergedString.TrimEnd(charsToTrim) + "}";
            Console.WriteLine(arrayMergedString);
            Console.ReadKey();
        }
    }

Note:

Optimizing for speed => creating new arrayMerged; optimization for space would require moving array1 elements in the else branch


来源: stackexchange

问:
Better way to edit Last item in Foreach loop
I have

```<code>var queryString = "";
foreach (var q in query)
{
    if (q.Equals(query.Last())
    {
       queryString += "'" + q.Trim() + "'";
    }
    else
    {
        queryString += "'" + q.Trim() + "', ";
    }
}
return queryString;
</code>```

However it feels rather clunky and unsophisticated. I'm convinced there is a better way to do it, but I haven't the foggiest, and Googling hasn't provided any better suggestions either.

答:
You could try something like this:

```<code>var queryString = string.Join(",", query.Select(item=>$"'{item.Trim()}'"));
</code>```

Essentially, you declare a sequence of the items that are in the query by Trimming them and enclosing them in single quotes and the using the string.Join you create a comma separated list of them.

ContentLicense: CC BY-SA 3.0

Body:
I have

var queryString = "";
foreach (var q in query)
{
    if (q.Equals(query.Last())
    {
       queryString += "'" + q.Trim() + "'";
    }
    else
    {
        queryString += "'" + q.Trim() + "', ";
    }
}
return queryString;

However it feels rather clunky and unsophisticated. I'm convinced there is a better way to do it, but I haven't the foggiest, and Googling hasn't provided any better suggestions either.

Body:
You could try something like this:

var queryString = string.Join(",", query.Select(item=>$"'{item.Trim()}'"));

Essentially, you declare a sequence of the items that are in the query by Trimming them and enclosing them in single quotes and the using the string.Join you create a comma separated list of them.


问:
How to use babel-runtime transform without an external dependency?
If I use the babel-plugin-transform-runtime plugin, then my code will import/require babel-runtime instead of including all those helper functions inline. This is nice, but it makes my library have a dependency babel-runtime. What I would rather do is have Babel extract one extra file (./babel-runtime) and drop that in with the other output files so that I don't have to include it as an external dependency. i.e., I won't have to add that to package.json everywhere my library is used. Is this possible?

答:
You can import custom module instead of babel-runtime by using the moduleName option in the transform-runtime plugin:

{
  "plugins": [
    ["transform-runtime", {
      "moduleName": "./babel-runtime"
    }]
  ]
}
```


问:
How to write Query with Multiple joins and having clause?
Fetch all the B_NAME having EST_ID = 10 and VALUE= 0 and  EST_ID = 11 and VALUE = 1 If EST_ID exists. </p>

<p>In the below example,  the output should be B1,  B2.  B4 Should not be selected as it has EST_ID=12 in it. </p>

```<code>ID  B_ID     B_NAME           EST_ID               VALUE
1      1          B1              10                0
2      1          B1              11                1
3      2          B2              10                0
4      3          B3              10                1
5      3          B3              11                0
6      4          B4              10                0
7      4          B4              11                1
8      4          B4              12                1
</code>```

答:
I don't know what query resulted you this, but you should try adding this at the end of your query:</p>

```<code>GROUP BY B_ID HAVING ((EST_ID=10 AND VALUE =0) || (EST_ID=11 AND VALUE =1)) AND B_ID <> 4
</code>```

Body:
Fetch all the B_NAME having EST_ID = 10 and VALUE= 0 and  EST_ID = 11 and VALUE = 1 If EST_ID exists.

In the below example,  the output should be B1,  B2.  B4 Should not be selected as it has EST_ID=12 in it.

ID  B_ID     B_NAME           EST_ID               VALUE
1      1          B1              10                0
2      1          B1              11                1
3      2          B2              10                0
4      3          B3              10                1
5      3          B3              11                0
6      4          B4              10                0
7      4          B4              11                1
8      4          B4              12                1

Body:
I don't know what query resulted you this, but you should try adding this at the end of your query:

GROUP BY B_ID HAVING ((EST_ID=10 AND VALUE =0) || (EST_ID=11 AND VALUE =1)) AND B_ID <> 4


问:
Strange behavior in a flexbox when resizing window on mobile chrome
There is a very strange behavior with flexbox happening on a mobile browser.

Please see this gif for a visual of what's happening

This only happens on a mobile browser, I'm currently using Chrome mobile on a Google Pixel phone. I have a resize script running that resizes multiple elements on the page as a workaround for not being able to properly utilize 100vh like so:

```<code>window.onresize = function() {
        document.getElementById("backgroundImage").style.height = window.innerHeight;
        document.getElementById("mainScreen").style.height = window.innerHeight;
        if (window.innerWidth > 750) {
          document.getElementById("scrollContent").style.height = window.innerHeight - "96";
        } else {
          document.getElementById("scrollContent").style.height = window.innerHeight - "72";
        }
    };
</code>```

The items that are being effected as seen in the gif are items in a flex container. This behavior happens when I scroll up to hide the navigation bar, then click one of the flex links.

I'm using Vuejs, and the content below is being populated by checking for a prop change. The flex links pass a string into a function that changes the project view to the selected project.

I also have a script to add a class that changes the background color on the selected link, and remove that class on all other links, which is how I am changing the active link background.

```<code>var webComp = Vue.component('design-comp', {
  template: "#webComp",
  props:['trans-state'],
  components: {
      'project-comp': projectComp,
  },
  data: function() {
    return {
      activeProj: 'default',
    }
  },
  methods: {
    changeProj: function(proj) {
      this.activeProj = proj;
      var a = document.getElementsByClassName('projClick');
      for (i=0; i<a.length; i++) {
        a[i].classList.remove('projActive');
      }
      event.currentTarget.classList.add('projActive');
      document.getElementById('webContainer').scrollTop = 0;
    }
  },
  created: function() {
    this.activeProj = "default";
  }
});
</code>```

Here is the relevant portion of my SASS file:

```<code>#webContainer {
  margin-top: 50px;
  height: calc(100% - 50px);
  .projHeader {
    display: flex;
    justify-content: center;
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    background-color: $headerColor;
    box-sizing: border-box;

    .projClick {
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      height: 50px;
      box-sizing: border-box;
      background-color: $contentColor;
      border-right: 2px solid $headerColor;
      border-left: 2px solid $headerColor;
      border-bottom: 4px solid $headerColor;
      border-top: 4px solid $headerColor;
      flex-basis: 50px;
      transition: background-color 0.3s;

      &.projActive {
        background-color: $linkActiveColor;
      }

      p {
        color: $fontColor;
        font-family: $titleFont;
        font-size: 2em;
      }
    }
  }
}
</code>```

Here is the relevant HTML:

```<code><div class="viewContainer" id="webContainer">
        <div class="transitionBox"></div>
        <div class="stickyImageBottomLeft"><img src="./img/AfricaMountainPixelR.gif" /></div>
        <div class="stickyImageBottomRight"><img src="./img/AfricaMountainPixel.gif" /></div>
        <div class="projHeader">
            <div class="projClick projActive" v-on:click="changeProj('default')">
                <p>0</p>
            </div>
            <div class="projClick" v-on:click="changeProj('kyount')">
                <p>1</p>
            </div>
            <div class="projClick" v-on:click="changeProj('prodigal')">
                <p>2</p>
            </div>
            <div class="projClick" v-on:click="changeProj('joy')">
                <p>3</p>
            </div>
            <div class="projClick" v-on:click="changeProj('cgl')">
                <p>4</p>
            </div>
            <div class="projClick" v-on:click="changeProj('mikeg')">
                <p>5</p>
            </div>
            <div class="projClick" v-on:click="changeProj('reddit')">
                <p>6</p>
            </div>
            <div class="projClick" v-on:click="changeProj('westbeach')">
                <p>7</p>
            </div>
        </div>
        <div class="contentContainer">
        Project Page is loaded here
        </div>
</div>
</code>```

I'm hoping someone might know what is going on because I really don't see a reason for this to be happening.

答:
Try this:</p>

```<code>#webContainer {
  margin: 0;
  padding-top: 50px;
  height: 100%;
  box-sizing: border-box; /* if you didn't apply it before */
...
</code>```

Body:
There is a very strange behavior with flexbox happening on a mobile browser.

Please see this gif for a visual of what's happening

This only happens on a mobile browser, I'm currently using Chrome mobile on a Google Pixel phone. I have a resize script running that resizes multiple elements on the page as a workaround for not being able to properly utilize 100vh like so:

window.onresize = function() {
        document.getElementById("backgroundImage").style.height = window.innerHeight;
        document.getElementById("mainScreen").style.height = window.innerHeight;
        if (window.innerWidth > 750) {
          document.getElementById("scrollContent").style.height = window.innerHeight - "96";
        } else {
          document.getElementById("scrollContent").style.height = window.innerHeight - "72";
        }
    };

The items that are being effected as seen in the gif are items in a flex container. This behavior happens when I scroll up to hide the navigation bar, then click one of the flex links.

I'm using Vuejs, and the content below is being populated by checking for a prop change. The flex links pass a string into a function that changes the project view to the selected project.

I also have a script to add a class that changes the background color on the selected link, and remove that class on all other links, which is how I am changing the active link background.

var webComp = Vue.component('design-comp', {
  template: "#webComp",
  props:['trans-state'],
  components: {
      'project-comp': projectComp,
  },
  data: function() {
    return {
      activeProj: 'default',
    }
  },
  methods: {
    changeProj: function(proj) {
      this.activeProj = proj;
      var a = document.getElementsByClassName('projClick');
      for (i=0; i<a.length; i++) {
        a[i].classList.remove('projActive');
      }
      event.currentTarget.classList.add('projActive');
      document.getElementById('webContainer').scrollTop = 0;
    }
  },
  created: function() {
    this.activeProj = "default";
  }
});

Here is the relevant portion of my SASS file:

#webContainer {
  margin-top: 50px;
  height: calc(100% - 50px);
  .projHeader {
    display: flex;
    justify-content: center;
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    background-color: $headerColor;
    box-sizing: border-box;

    .projClick {
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      height: 50px;
      box-sizing: border-box;
      background-color: $contentColor;
      border-right: 2px solid $headerColor;
      border-left: 2px solid $headerColor;
      border-bottom: 4px solid $headerColor;
      border-top: 4px solid $headerColor;
      flex-basis: 50px;
      transition: background-color 0.3s;

      &.projActive {
        background-color: $linkActiveColor;
      }

      p {
        color: $fontColor;
        font-family: $titleFont;
        font-size: 2em;
      }
    }
  }
}

Here is the relevant HTML:

0

1

2

3

4

5

6

7

        Project Page is loaded here

I'm hoping someone might know what is going on because I really don't see a reason for this to be happening.

Body:
Try this:

#webContainer {
  margin: 0;
  padding-top: 50px;
  height: 100%;
  box-sizing: border-box; /* if you didn't apply it before */
...


问:
Handling scroll Animation in React
What is the correct way of dealing with scroll position in React? I really like smooth scrolling because of better UX. Since manipulating the DOM in React is an anti-pattern I ran into problem: how to scroll smoothly to some position/element? I usually change scrollTop value of an element, but this is a manipulation on the DOM, which is not allowed.

JSBIN

code:

```<code>import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component {
  handleClick = e => {
    for (let i = 1; i <= 100; i++) {
      setTimeout(() => (this.node.scrollTop = i), i * 2);
    }
  };

  render() {
    const someArrayToMap = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    return (
      <div ref={node => this.node = node} style={{overflow: 'auto', height: '100vh'}}>
        <button onClick={this.handleClick}>CLICK TO SCROLL</button>
        {
            [...someArrayToMap,
            ...someArrayToMap,
            ...someArrayToMap,
            ...someArrayToMap,
            ...someArrayToMap,
            ...someArrayToMap,
            ...someArrayToMap].map((e, i) => <div key={i}>some text here</div>)
        }
      </div>
    );
  }
}

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

How to achieve this in a React way?

答:
A couple good packages out there already that can handle this for you:

https://github.com/fisshy/react-scroll - Demo

https://www.npmjs.com/package/react-scroll-to-component
Simple scroll to component

Hope this helps!

Title: Handling scroll Animation in React

Body:
What is the correct way of dealing with scroll position in React? I really like smooth scrolling because of better UX. Since manipulating the DOM in React is an anti-pattern I ran into problem: how to scroll smoothly to some position/element? I usually change scrollTop value of an element, but this is a manipulation on the DOM, which is not allowed.

JSBIN

code:

import React from 'react';
import ReactDOM from 'react-dom';

class App extends React.Component {
  handleClick = e => {
    for (let i = 1; i <= 100; i++) {
      setTimeout(() => (this.node.scrollTop = i), i * 2);
    }
  };

  render() {
    const someArrayToMap = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

    return (

 this.node = node} style={{overflow: 'auto', height: '100vh'}}>
        <button onClick={this.handleClick}>CLICK TO SCROLL</button>
        {
            [...someArrayToMap,
            ...someArrayToMap,
            ...someArrayToMap,
            ...someArrayToMap,
            ...someArrayToMap,
            ...someArrayToMap,
            ...someArrayToMap].map((e, i) =>
some text here
)
        }

    );
  }
}

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

How to achieve this in a React way?


问:
Set Background in a LinearLayout from byte array
I have a LinearLayout with a default Background, but in some circumstances I need to set a custom Background from a byte[] data from Blob object in SQL Database.
I alreay have made the custom Adapter but I have no idea how do the image part.</p>

```<code>if (Ad.getAd_image().length > 0) {
    //Ad.getAd_image() is a byte[] object
    ad_image_layout.setBackground(???);
}
</code>```

答:
do this</p>

```<code>Bitmap bitmap=BitmapFactory.decodeByteArray(Ad.getAd_image(),0,Ad.getAd_image().length);

Drawable d = new BitmapDrawable(getResources(), bitmap);

LinearLayout l;
l=(LinearLayout)findViewById(R.id.layout_id)
l.setBackground(d);
</code>```

Body:
I have a LinearLayout with a default Background, but in some circumstances I need to set a custom Background from a byte[] data from Blob object in SQL Database.
I alreay have made the custom Adapter but I have no idea how do the image part.

if (Ad.getAd_image().length > 0) {
    //Ad.getAd_image() is a byte[] object
    ad_image_layout.setBackground(???);
}

Body:
do this

Bitmap bitmap=BitmapFactory.decodeByteArray(Ad.getAd_image(),0,Ad.getAd_image().length);

Drawable d = new BitmapDrawable(getResources(), bitmap);

LinearLayout l;
l=(LinearLayout)findViewById(R.id.layout_id)
l.setBackground(d);


问:
PHP 7, Imagemagick and CircleCI
Does anybody know how to install php 7 with ImageMagick on CircleCI?

Everything except ImageMagick works. Here is the error message I get.

```<code>Intervention\Image\Exception\NotSupportedException:
ImageMagick module not available with this PHP installation.
</code>```

Here is my circle.yml

```<code>machine:
  pre:
    - sudo apt-get update; USE_PRECOMPILE=true sudo -E circleci-install php 7.0.4
  php:
    version: 7.0.4
  timezone: America/Los_Angeles

  services:
    - mysql

  environment:
      APP_ENV: testing
      APP_KEY: randomrandomrandomrandomrandomra

dependencies:
  pre:
    - sudo aptitude -y install imagemagick
    - sudo apt-add-repository -y ppa:ondrej/php
    - sudo apt-get -y update
    - sudo apt-get -y install php-imagick

  override:
    - composer install --prefer-dist --no-interaction

  post:
    - mv .env.circleci .env

test:
  override:
    - vendor/bin/phpunit
</code>```

答:
To get imagick working with PHP 7 you need to use the following in your circle.yml:

```<code>machine:
  php:
    version: 7.1.3

dependencies:
  pre:
    - printf "\n" | pecl install -f imagick
    - echo "extension = imagick.so" >> /opt/circleci/php/$(phpenv global)/etc/php.ini
</code>```

Hope this helps!

Title: PHP 7, Imagemagick and CircleCI

Body:
Does anybody know how to install php 7 with ImageMagick on CircleCI?

Everything except ImageMagick works. Here is the error message I get.

Intervention\Image\Exception\NotSupportedException:
ImageMagick module not available with this PHP installation.

Here is my circle.yml

machine:
  pre:
    - sudo apt-get update; USE_PRECOMPILE=true sudo -E circleci-install php 7.0.4
  php:
    version: 7.0.4
  timezone: America/Los_Angeles

  services:
    - mysql

  environment:
      APP_ENV: testing
      APP_KEY: randomrandomrandomrandomrandomra

dependencies:
  pre:
    - sudo aptitude -y install imagemagick
    - sudo apt-add-repository -y ppa:ondrej/php
    - sudo apt-get -y update
    - sudo apt-get -y install php-imagick

  override:
    - composer install --prefer-dist --no-interaction

  post:
    - mv .env.circleci .env

test:
  override:
    - vendor/bin/phpunit

Body:
To get imagick working with PHP 7 you need to use the following in your circle.yml:

machine:
  php:
    version: 7.1.3

dependencies:
  pre:
    - printf "\n" | pecl install -f imagick
    - echo "extension = imagick.so" >> /opt/circleci/php/$(phpenv global)/etc/php.ini

Hope this helps!


问:
How to create n strings of random lengths the sum of which is equal to a given amount?
I'm trying to create an algorithm to create n strings of random length the sum of which is equal to a given amount.

An example to make it clearer:

```<code>total = 20;
n = 7;

strings = ['aaaa', 'a', 'aaaaaaa', 'aa', 'aaa', 'aa', 'a'];
</code>```

So I have 7 strings of random lengths and the sum of their individual lengths is (unless I made an error counting) 20.

Till now I came up with this recursive function:

```<code>gaps = [];
function createGapsArray(total, n) {
    if (n == 1) {
        var gapLength = total;
    } else {
        var gapLength = getRandomInt(1, total / 2);
    }

  var gap = "";
  for (var i = 0; i < gapLength; i++) {
    gap += "a";
  }
  gaps.push(gap);

  if (n > 1 && total > 0) {
    createGapsArray(total - gapLength, --n);
  }
}
</code>```

Which doesn't really work. Usually it finishes before generating all the n segments I want. With the few tests that I've done, it seems that dividing the total by 4 instead of 2, gets the job done. Like:

```<code>var gapLength = getRandomInt(1, total / 4);
</code>```

But the choice of this constraint is just arbitrary. I'm wondering if there is a better approach to this.

Also, I'm aware that with my approach the algorithm is likely to generate longer segments at first and smaller ones towards the end. I wouldn't mind an even distribution, but it's not a big deal because for what I need it I can simply shuffle the array once it's done.

答:
The way to think of it is as having string of characters of length equal to total. I'll use 20 as an example:

```<code>string: aaaaaaaaaaaaaaaaaaaa
index:  01234567890123456789
</code>```

You then generate N-1 random numbers between 0 and total that correspond to the positions that you should cut the string to generate N different strings.

Lets say the numbers are 5, 8, 13, 15, 1, 3. These will be the indices to cut the string:

```<code>string: a aa aa aaa aaaaa aa aaaaa
index:  0|12|34|567|89012|34|56789
</code>```

This is the same as generating N-1 random numbers, sorting them, adding 0 at the beginning of the list and total at the end, and taking the difference:

```<code>var numbers = [0];
for (var i = 0; i < N-1; i++) numbers.push(getRandomInt(0, total));
numbers.push(total);
numbers.sort();

var strings = [];
for (var i = 0; i < N; i++)
  strings.push(new Array(numbers[i + 1] - numbers[i]).join('a'));
</code>```

This will give a uniform distribution.

Note that if you want only non-empty strings there should be no duplicate random values.

Body:
I'm trying to create an algorithm to create n strings of random length the sum of which is equal to a given amount.

An example to make it clearer:

total = 20;
n = 7;

strings = ['aaaa', 'a', 'aaaaaaa', 'aa', 'aaa', 'aa', 'a'];

So I have 7 strings of random lengths and the sum of their individual lengths is (unless I made an error counting) 20.

Till now I came up with this recursive function:

gaps = [];
function createGapsArray(total, n) {
    if (n == 1) {
        var gapLength = total;
    } else {
        var gapLength = getRandomInt(1, total / 2);
    }

  var gap = "";
  for (var i = 0; i < gapLength; i++) {
    gap += "a";
  }
  gaps.push(gap);

  if (n > 1 && total > 0) {
    createGapsArray(total - gapLength, --n);
  }
}

Which doesn't really work. Usually it finishes before generating all the n segments I want. With the few tests that I've done, it seems that dividing the total by 4 instead of 2, gets the job done. Like:

var gapLength = getRandomInt(1, total / 4);

But the choice of this constraint is just arbitrary. I'm wondering if there is a better approach to this.

Also, I'm aware that with my approach the algorithm is likely to generate longer segments at first and smaller ones towards the end. I wouldn't mind an even distribution, but it's not a big deal because for what I need it I can simply shuffle the array once it's done.

Body:
The way to think of it is as having string of characters of length equal to total. I'll use 20 as an example:

string: aaaaaaaaaaaaaaaaaaaa
index:  01234567890123456789

You then generate N-1 random numbers between 0 and total that correspond to the positions that you should cut the string to generate N different strings.

Lets say the numbers are 5, 8, 13, 15, 1, 3. These will be the indices to cut the string:

string: a aa aa aaa aaaaa aa aaaaa
index:  0|12|34|567|89012|34|56789

This is the same as generating N-1 random numbers, sorting them, adding 0 at the beginning of the list and total at the end, and taking the difference:

var numbers = [0];
for (var i = 0; i < N-1; i++) numbers.push(getRandomInt(0, total));
numbers.push(total);
numbers.sort();

var strings = [];
for (var i = 0; i < N; i++)
  strings.push(new Array(numbers[i + 1] - numbers[i]).join('a'));

This will give a uniform distribution.

Note that if you want only non-empty strings there should be no duplicate random values.


问:
Angular Js- Is there any way to generate dynamically checkbox which are also preselected?
I have been wandering for two to three hours and I found chunks of relevant questions but my scenario just take a little curve. I have to generate a number of checkboxes which obviously would be generated through ng-repeat. How can I show the preselected values which I am getting from Api. Here is the kind of data I am receiving.

Pre-selected data

```<code>$scope.categoriess = [{"id":1,"name":"Garden Cleaning"},{"id":3,"name":"Home Cleaning"}].
</code>```

and this is the data over which I am using ng-repeat.

ng-repeat data

```<code>$scope.categories = [{"id":1,"name":"Garden Cleaning"},{"id":2,"name":"Gutter Cleaning"},{"id":3,"name":"Home Cleaning"},{"id":4,"name":"Pool Cleaning"}
</code>```

HTML

```<code>  <div ng-repeat="cats in categories">
      <input type="checkbox" ng-model="categoriess.id[cats.id]">
               <label>{{cats.name}}</label>
                  </div>
</code>```

Now how would i tell ng-repeat to check the preselected data, plus if I want to check few more boxes they should also be checked and I want them to store in $scope.categoriess. I have tried a number of solution either with ng-checked or by make a function call in ng-checked I got no expected results.

答:
Change your html like this :

```<code><div ng-repeat="cats in categories">
   <input type="checkbox" ng-model="categoriess.id[cats.id]" ng-checked="isChecked(cats.id);">
   <label>{{cats.name}}</label>
</div>
</code>```

Add this function in your controller :

```<code>$scope.selectedCategoriess = [{"id":1,"name":"Garden Cleaning"},{"id":3,"name":"Home Cleaning"}].

$scope.isChecked = function(id){
for (var i = 0; i < $scope.selectedCategoriess.length; i++) {
    if ($scope.selectedCategoriess[i].id == id) {
        return true;
    }
}
return false;
}
</code>```

If id is available checked value will be "true".

Body:
I have been wandering for two to three hours and I found chunks of relevant questions but my scenario just take a little curve. I have to generate a number of checkboxes which obviously would be generated through ng-repeat. How can I show the preselected values which I am getting from Api. Here is the kind of data I am receiving.

Pre-selected data

$scope.categoriess = [{"id":1,"name":"Garden Cleaning"},{"id":3,"name":"Home Cleaning"}].

and this is the data over which I am using ng-repeat.

ng-repeat data

$scope.categories = [{"id":1,"name":"Garden Cleaning"},{"id":2,"name":"Gutter Cleaning"},{"id":3,"name":"Home Cleaning"},{"id":4,"name":"Pool Cleaning"}

HTML

      <input type="checkbox" ng-model="categoriess.id[cats.id]">
               {{cats.name}}

Now how would i tell ng-repeat to check the preselected data, plus if I want to check few more boxes they should also be checked and I want them to store in $scope.categoriess. I have tried a number of solution either with ng-checked or by make a function call in ng-checked I got no expected results.

Body:
Change your html like this :

<div ng-repeat="cats in categories">
   <input type="checkbox" ng-model="categoriess.id[cats.id]" ng-checked="isChecked(cats.id);">
   <label>{{cats.name}}</label>
</div>

Add this function in your controller :

$scope.selectedCategoriess = [{"id":1,"name":"Garden Cleaning"},{"id":3,"name":"Home Cleaning"}].

$scope.isChecked = function(id){
for (var i = 0; i < $scope.selectedCategoriess.length; i++) {
    if ($scope.selectedCategoriess[i].id == id) {
        return true;
    }
}
return false;
}

If id is available checked value will be "true".


问:
From How far can the camera look an object in OpenGl in android?
I am new to OpenGL android, but know some basic concepts like projection and camera views.
we can change the position and orientation of camera. But,when i move camera more away from an object the object disappears .
For example: Below is my camera view and the co-ordinates of rectangle.

```<code>Matrix.setLookAtM(mViewMatrix, 0, 0, 0, -7, 0f, 0f, 0f, 0f, 1.0f, 0.0f);

float rectCoords[] = {
        -0.5f, 0.5f, 0.0f,
        -0.5f, -0.5f, 0.0f,
        0.5f, 0.5f, 0.0f,
        0.5f, -0.5f, 0.0f,
};
</code>```

if I am correct the camera is 7 units away from the rectangle which is on XY plane and camera is 7 units away from rectangle on negative z axis looking towards the origin whose top is pointing towards positive y-axis.

When I change -7.0f i.e the z coordinate of the camera, to -7.1f(i.e i am moving the camera away from the rectangle) the rectangle disappears, that means the maximum distance the camera can see is 7 units from it. Correct me if i am wrong, if not then how can i make to see the object more than 7 units visible from camera

答:
bro!if u hav a myReshape function in your code,,,just go to gluperspective() function,,in that increase the last value...ur issue will be solved.

ex: gluPerspective (60, (GLfloat)w / (GLfloat)h, 0.1, 500.0);

increase 500.0 to 1000.0

Body:
I am new to OpenGL android, but know some basic concepts like projection and camera views.
we can change the position and orientation of camera. But,when i move camera more away from an object the object disappears .
For example: Below is my camera view and the co-ordinates of rectangle.

Matrix.setLookAtM(mViewMatrix, 0, 0, 0, -7, 0f, 0f, 0f, 0f, 1.0f, 0.0f);

float rectCoords[] = {
        -0.5f, 0.5f, 0.0f,
        -0.5f, -0.5f, 0.0f,
        0.5f, 0.5f, 0.0f,
        0.5f, -0.5f, 0.0f,
};

if I am correct the camera is 7 units away from the rectangle which is on XY plane and camera is 7 units away from rectangle on negative z axis looking towards the origin whose top is pointing towards positive y-axis.

When I change -7.0f i.e the z coordinate of the camera, to -7.1f(i.e i am moving the camera away from the rectangle) the rectangle disappears, that means the maximum distance the camera can see is 7 units from it. Correct me if i am wrong, if not then how can i make to see the object more than 7 units visible from camera


问:
Handling data from csv file with Python
I know Python is almost made for these kind of purposes, but I am really struggling to understand how I get access to specific values in the dataset, and I tried both with pandas and csv modules. It is probably a matter of syntax. Here's the thing: I have a csv file in the form of

```<code>Nation, Year, No. of refugees
Afghanistan,2013,6657
Albania,2013,199
Algeria,2013,91
Angola,2013,47
Armenia,2013,156
...
...
Afghanistan,2012,6960
Albania,2012,157
Algeria,2012,67
Angola,2012,43
Armenia,2012,143
...
</code>```

and so on. What I would like to do is to get the total amount of refugees per year, i.e. selecting all the rows with a certain year and summing all the elements in the related "no. of refugees" column. I managed to do this:

```<code>import csv

with open('refugees.csv', 'r') as f:
    d_reader = csv.DictReader(f)
    headers = d_reader.fieldnames
    print headers

    #2013
    list2013=[]
    for line in d_reader:
        if (line['Year']=='2013'):
            list2013.append(line['Refugees'])
    list2013=map(int,list2013) #I have str values in my file
    ref13=sum(list2013)
</code>```

but I am looking for a more elegant (and, above all, iterative) solution. Moreover, if I perform that procedure multiple times for different years, I always get 0: it works for 2013 only, not sure why.

Edit: I tried this as well, without success, but I think this could be totally wrong:

```<code>import csv
refugees_dict={}
a=range(2005,2014)
a=map(str, a)
with open('refugees.csv', 'r') as f:
    d_reader = csv.DictReader(f)

    for element in a:
        for line in d_reader:
            if (line['Year']==element):
                print 'hello!'
                temp_list=[]
                temp_list.append(line['Refugees'])
                temp_list=map(int, temp_list)
                refugees_dict[a]=sum(temp_list)

print refugees_dict
</code>```

The next step of my work will involve further studies on the dataset, eg I am probably gonna need to access data nation-wise instead of year-wise, and I really appreciate any hint so I understand how to manipulate data.
Thanks a lot.

答:
Consider:

```<code>from collections import defaultdict
by_year = defaultdict(int)  # a dict that has a 0 under every key.
</code>```

and then

```<code>by_year[line['year']] += int(line['Refugees'])
</code>```

Now you can just look at by_year['2013'] and see your sum (same for other years).

Title: Handling data from csv file with Python

Body:
I know Python is almost made for these kind of purposes, but I am really struggling to understand how I get access to specific values in the dataset, and I tried both with pandas and csv modules. It is probably a matter of syntax. Here's the thing: I have a csv file in the form of

Nation, Year, No. of refugees
Afghanistan,2013,6657
Albania,2013,199
Algeria,2013,91
Angola,2013,47
Armenia,2013,156
...
...
Afghanistan,2012,6960
Albania,2012,157
Algeria,2012,67
Angola,2012,43
Armenia,2012,143
...

and so on. What I would like to do is to get the total amount of refugees per year, i.e. selecting all the rows with a certain year and summing all the elements in the related "no. of refugees" column. I managed to do this:

import csv

with open('refugees.csv', 'r') as f:
    d_reader = csv.DictReader(f)
    headers = d_reader.fieldnames
    print headers

    #2013
    list2013=[]
    for line in d_reader:
        if (line['Year']=='2013'):
            list2013.append(line['Refugees'])
    list2013=map(int,list2013) #I have str values in my file
    ref13=sum(list2013)

but I am looking for a more elegant (and, above all, iterative) solution. Moreover, if I perform that procedure multiple times for different years, I always get 0: it works for 2013 only, not sure why.

Edit: I tried this as well, without success, but I think this could be totally wrong:

import csv
refugees_dict={}
a=range(2005,2014)
a=map(str, a)
with open('refugees.csv', 'r') as f:
    d_reader = csv.DictReader(f)

    for element in a:
        for line in d_reader:
            if (line['Year']==element):
                print 'hello!'
                temp_list=[]
                temp_list.append(line['Refugees'])
                temp_list=map(int, temp_list)
                refugees_dict[a]=sum(temp_list)

print refugees_dict

The next step of my work will involve further studies on the dataset, eg I am probably gonna need to access data nation-wise instead of year-wise, and I really appreciate any hint so I understand how to manipulate data.
Thanks a lot.

Body:
Consider:

from collections import defaultdict
by_year = defaultdict(int)  # a dict that has a 0 under every key.

and then

by_year[line['year']] += int(line['Refugees'])

Now you can just look at by_year['2013'] and see your sum (same for other years).


问:
Angular 2 material nested md-list-item
Using Angular 2 with material design, trying to get nested lists in sidenav
I have code like

```<code><md-sidenav #sidenav class="sidenav" mode="over" opened>
    <md-nav-list>
           <md-card class="user-card">
               <md-card-header>
                 <div md-card-avatar class="user-avatar"></div>
               </md-card-header>
           </md-card>
      <md-divider></md-divider>
      <md-list-item *ngFor="let category of ategories">
         <a md-line>{{ category.name }}</a>
      </md-list-item>
    </md-nav-list>
</md-sidenav>
</code>```

which works fine and looks something like

Now When i try to nest it, like

```<code><md-sidenav #sidenav class="sidenav" mode="over" opened>
    <md-nav-list>
           <md-card class="user-card">
               <md-card-header>
                 <div md-card-avatar class="user-avatar"></div>
               </md-card-header>
           </md-card>
      <md-divider></md-divider>
      <md-list-item *ngFor="let category of ategories">
         <a md-line>{{ category.name }}</a>
         <md-list-item *ngFor="let subcategory of category.subcategories">
            <a md-line>{{ subcategory.subcategory }}</a>
         </md-list-item>
      </md-list-item>
    </md-nav-list>
</md-sidenav>
</code>```

It appears like

I want to achieve nested list, probably collapsible.
Any idea what am i doing wrong or how to approach this ?

答:
Ok, figured it out, if someone in future gets stuck like this.

Do no *ngfor on md-list-item, rather do it on div, like this

```<code>            <md-list>
                <div  *ngFor="let category of practice_categories">
                    <md-list-item>{{category.category}}</md-list-item>
                    <md-list style="margin-left:30px;">
                          <div *ngFor="let subcategory of category.subcategories">
                            <md-list-item>{{ subcategory.subcategory }}</md-list-item>
                          </div>
                    </md-list>
                </div>
            </md-list>
</code>```

which produces something like

Hope this helps someone, someday

Title: Angular 2 material nested md-list-item

Body:
Using Angular 2 with material design, trying to get nested lists in sidenav
I have code like

<md-sidenav #sidenav class="sidenav" mode="over" opened>
    <md-nav-list>
           <md-card class="user-card">
               <md-card-header>

               </md-card-header>
           </md-card>
      <md-divider></md-divider>
      <md-list-item *ngFor="let category of ategories">
         {{ category.name }}
      </md-list-item>
    </md-nav-list>
</md-sidenav>

which works fine and looks something like

Now When i try to nest it, like

<md-sidenav #sidenav class="sidenav" mode="over" opened>
    <md-nav-list>
           <md-card class="user-card">
               <md-card-header>

               </md-card-header>
           </md-card>
      <md-divider></md-divider>
      <md-list-item *ngFor="let category of ategories">
         {{ category.name }}
         <md-list-item *ngFor="let subcategory of category.subcategories">
            {{ subcategory.subcategory }}
         </md-list-item>
      </md-list-item>
    </md-nav-list>
</md-sidenav>

It appears like

I want to achieve nested list, probably collapsible.
Any idea what am i doing wrong or how to approach this ?

Body:
Ok, figured it out, if someone in future gets stuck like this.

Do no *ngfor on md-list-item, rather do it on div, like this

            <md-list>
                <div  *ngFor="let category of practice_categories">
                    <md-list-item>{{category.category}}</md-list-item>
                    <md-list style="margin-left:30px;">
                          <div *ngFor="let subcategory of category.subcategories">
                            <md-list-item>{{ subcategory.subcategory }}</md-list-item>
                          </div>
                    </md-list>
                </div>
            </md-list>

which produces something like

Hope this helps someone, someday


问:
Resizing CATiledLayer's Using Scale Transforms vs. Bounds Manipulation
I've got my layer hosted workspace working so that using CATiledLayers for hundreds of images works nicely when the workspace is zoomed out substantially. All the images use lower resolution representations, and my application is much more responsive when panning and zooming large numbers of images.

However, within my application I also provide the user the ability to resize layers with a resize handle. Before I converted image layers to use CATiledLayers I was doing layer resizes by manipulating the bounds of the image layer according to the resize delta (mouse drag), and it worked well. But now with CATiledLayers in place, this is causing CATiledLayers to get confused when I mix resizing of layers through bounds manipulation and zooming/unzooming the workspace through scale transforms.

Specifically, if I resize a CATiledLayer to half the width/height size (1/4 the area), the image inside it will suddenly scale to a further 1/2 the resized frame leaving 3/4 of the frame empty. This seems to be exactly when the inner CATiledLayer logic gets invoked to provide a lower resolution image representation. It works fine if I don't touch the resize handler and just zoom/unzoom the workspace.

Is there a way to make zooming/resizing play nice together with CATiledLayers, or am I going to have to convert my layer resize logic to use scale transforms instead of bounds manipulations?

答:
I ended up solving this by converting my layer resize logic to use scale transforms by overriding the setBounds: method for my custom image layer class to scale it's containing CATiledLayer, and repositioning accordingly. Also it is important to make sure the CATiledLayer's autoresizingMask is set to kCALayerNotSizable since we are handling resizes manually in setBounds:.

Note: be sure to call the superclass's implementation of setBounds:.

ContentLicense: CC BY-SA 2.5


问:
Android ADB devices unauthorized

Configuration:

Windows 8.1

ADB version: 1.0.32

Smartphone: Oneplus One

Problem

I installed the Samsung drivers as it is said to do. When I run the ADB devices command, it said unauthorized.

Already tried:

I've done everything that'd been said on this post: https://stackoverflow.com/a/25546300/1848376

But the problem is that I don't get a prompt on the phone to tell me I must accept the connection.

When I run the command adb shell, here is the answer:

```<code>error: device unauthorized.
This adbd's $ADB_VENDOR_KEYS is not set; try 'adb kill-server' if that seems wrong.
Otherwise check for a confirmation dialog on your device.
</code>```

I did "adb kill-server", but it didn't change anything. Why?

答: Ensure that you have accepted the pressed the "ok" button when it is asking it is showing the fingerprint of the device after connecting through usb to your PC. </p>

ContentLicense: CC BY-SA 4.0

Title: Android ADB devices unauthorized

Body:
Configuration:

Windows 8.1

ADB version: 1.0.32

Smartphone: Oneplus One

Problem

I installed the Samsung drivers as it is said to do. When I run the ADB devices command, it said unauthorized.

Already tried:

I've done everything that'd been said on this post: https://stackoverflow.com/a/25546300/1848376

But the problem is that I don't get a prompt on the phone to tell me I must accept the connection.

When I run the command adb shell, here is the answer:

error: device unauthorized.
This adbd's $ADB_VENDOR_KEYS is not set; try 'adb kill-server' if that seems wrong.
Otherwise check for a confirmation dialog on your device.

I did "adb kill-server", but it didn't change anything. Why?


问:
Foreach Checked and click event knockout
I would like to add the values of 'Cost' based on checkbox checked event on knock out.

```<code><tbody data-bind="foreach: $root.searchedResults">
    <!-- ko if: Id-->
    <tr>
        <td data-bind="text: Id"></td>
        <td data-bind="text: Cost"></td>
        <td><input type="checkbox" data-bind="checked: $root.searchedResults().length > 0, click: $root.Hospital_click"></td>
    </tr>
    <!-- /ko -->
</tbody>
</code>```

And the sum of cost should be displayed in

```<code><div data-bind="text: ko.toJSON(SumofItems)"></div>
</code>```

The click event is not updating my sum based selection. Can someone help?

```<code>self.Hospital_click = function () {
    //Suggest
}
</code>```

My View  model is:

```<code>var SearchModel = function () {

    var self = this;
    self.searchFromDate = ko.observable('01/01/2014');
    self.searchToDate = ko.observable('01/01/2016');

    self.searchedResults = ko.observableArray([]);

    self.search = function () {

        var model = {
            BeginDate: self.searchFromDate(),
            EndDate: self.searchToDate()
        };

        $.ajax({
            url: '@Url.Action("SearchSpend", "Analysis", new { Area = "Portal" })',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            dataType: "json",
            data: ko.toJSON(model),

            success: function (response) {
                self.searchedResults(response);

            }
        });

    };
</code>```

答:
You could add a new observableArray with the id's of the selected results (selectedResults).  The viewmodel could be:

```<code>    function Result(id,cost) {
        this.Id = id;
        this.Cost = cost;
    }

    function viewModel() {

        var self = this;

        self.searchedResults = ko.observableArray([]);

        self.selectedResults = ko.observableArray([])

        self.totalCost = ko.computed(function() {
            let total = 0;
            for(let p = 0; p < self.searchedResults().length; ++p)
            {
                if (self.selectedResults.indexOf(self.searchedResults()[p].Id)>=0){
                    total += self.searchedResults()[p].Cost;
                }
            }
            return total;
        });

    };
</code>```

totalCost will return the sum of the Cost field for all selected results.

And the view could be something like this:

```<code>    <table data-bind="foreach: searchedResults">
        <tr>
            <td data-bind="text: Id"></td>
            <td data-bind="text: Cost"></td>
            <td><input type="checkbox" value="" data-bind="checkedValue: Id, checked: $parent.selectedResults"></td>
        </tr>
    </table>

    <div data-bind="text: totalCost"></div>
</code>```

totalCost is a computed value that returns de sum of the Cost for only the selected results.

Here is a fiddle.

In the fiddle, the data comes from the array listOfResults.  In your case, this comes from the success function (Ajax request); in this function you also needs to clean the selectedResults.

Body:
I would like to add the values of 'Cost' based on checkbox checked event on knock out.

        <input type="checkbox" data-bind="checked: $root.searchedResults().length > 0, click: $root.Hospital_click">

And the sum of cost should be displayed in

The click event is not updating my sum based selection. Can someone help?

self.Hospital_click = function () {
    //Suggest
}

My View  model is:

var SearchModel = function () {

    var self = this;
    self.searchFromDate = ko.observable('01/01/2014');
    self.searchToDate = ko.observable('01/01/2016');

    self.searchedResults = ko.observableArray([]);

    self.search = function () {

        var model = {
            BeginDate: self.searchFromDate(),
            EndDate: self.searchToDate()
        };

        $.ajax({
            url: '@Url.Action("SearchSpend", "Analysis", new { Area = "Portal" })',
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            dataType: "json",
            data: ko.toJSON(model),

            success: function (response) {
                self.searchedResults(response);

            }
        });

    };

Body:
You could add a new observableArray with the id's of the selected results (selectedResults).  The viewmodel could be:

    function Result(id,cost) {
        this.Id = id;
        this.Cost = cost;
    }

    function viewModel() {

        var self = this;

        self.searchedResults = ko.observableArray([]);

        self.selectedResults = ko.observableArray([])

        self.totalCost = ko.computed(function() {
            let total = 0;
            for(let p = 0; p < self.searchedResults().length; ++p)
            {
                if (self.selectedResults.indexOf(self.searchedResults()[p].Id)>=0){
                    total += self.searchedResults()[p].Cost;
                }
            }
            return total;
        });

    };

totalCost will return the sum of the Cost field for all selected results.

And the view could be something like this:

    <table data-bind="foreach: searchedResults">
        <tr>
            <td data-bind="text: Id"></td>
            <td data-bind="text: Cost"></td>
            <td><input type="checkbox" value="" data-bind="checkedValue: Id, checked: $parent.selectedResults"></td>
        </tr>
    </table>

    <div data-bind="text: totalCost"></div>

totalCost is a computed value that returns de sum of the Cost for only the selected results.

Here is a fiddle.

In the fiddle, the data comes from the array listOfResults.  In your case, this comes from the success function (Ajax request); in this function you also needs to clean the selectedResults.


问:
GAE Endpoints firebase: Authentication Users TypeError: issuers type doesn't match <type 'dict'>
I am following this tutorial for user authentication on GAE, endpoints v2 in Python.
I use their code EXACTLY (only pasting in my app ID).
Running the code locally via PyCharm, it doesn't like the type of "issuers" wanting a dict: TypeError: issuers type doesn't match .

Has it something to do with IDE integration not being supported yet? What am I overlooking?

In full:

```<code>ERROR    2017-06-05 15:23:19,417 wsgi.py:263]
Traceback (most recent call last):
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\runtime\wsgi.py", line 240, in Handle
    handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\runtime\wsgi.py", line 299, in _LoadHandler
    handler, path, err = LoadObject(self._handler)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\runtime\wsgi.py", line 85, in LoadObject
    obj = __import__(path[0])
  File "C:\Users(...)\web app\goal.py", line 103, in <module>
    issuers=[firebase_issuer])
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\protorpc-1.0\protorpc\util.py", line 173, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Users\(...)\web app\lib\endpoints\api_config.py", line 976, in api
    api_key_required=api_key_required, base_path=base_path)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\protorpc-1.0\protorpc\util.py", line 173, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Users\(...)\web app\lib\endpoints\api_config.py", line 469, in __init__
    base_path=base_path)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\protorpc-1.0\protorpc\util.py", line 173, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Users\(...)\web app\lib\endpoints\api_config.py", line 550, in __init__
    _CheckType(issuers, dict, 'issuers')
  File "C:\Users\(...)\web app\lib\endpoints\api_config.py", line 195, in _CheckType
    raise TypeError('%s type doesn\'t match %s.' % (name, check_type))
TypeError: issuers type doesn't match <type 'dict'>.
</code>```

答: Apologies for the incorrect documentation. You do need to pass a dict. So try issuers={'firebase': firebase_issuer} instead.

Body:
I am following this tutorial for user authentication on GAE, endpoints v2 in Python.
I use their code EXACTLY (only pasting in my app ID).
Running the code locally via PyCharm, it doesn't like the type of "issuers" wanting a dict: TypeError: issuers type doesn't match .

Has it something to do with IDE integration not being supported yet? What am I overlooking?

In full:

ERROR    2017-06-05 15:23:19,417 wsgi.py:263]
Traceback (most recent call last):
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\runtime\wsgi.py", line 240, in Handle
    handler = _config_handle.add_wsgi_middleware(self._LoadHandler())
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\runtime\wsgi.py", line 299, in _LoadHandler
    handler, path, err = LoadObject(self._handler)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\runtime\wsgi.py", line 85, in LoadObject
    obj = __import__(path[0])
  File "C:\Users(...)\web app\goal.py", line 103, in <module>
    issuers=[firebase_issuer])
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\protorpc-1.0\protorpc\util.py", line 173, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Users\(...)\web app\lib\endpoints\api_config.py", line 976, in api
    api_key_required=api_key_required, base_path=base_path)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\protorpc-1.0\protorpc\util.py", line 173, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Users\(...)\web app\lib\endpoints\api_config.py", line 469, in __init__
    base_path=base_path)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\lib\protorpc-1.0\protorpc\util.py", line 173, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "C:\Users\(...)\web app\lib\endpoints\api_config.py", line 550, in __init__
    _CheckType(issuers, dict, 'issuers')
  File "C:\Users\(...)\web app\lib\endpoints\api_config.py", line 195, in _CheckType
    raise TypeError('%s type doesn\'t match %s.' % (name, check_type))
TypeError: issuers type doesn't match <type 'dict'>.


问:
Bash loop thru files not working as expected
Why is my code below not working as expected?

```<code>shopt -s extglob || {

    echo "Unable to enable exglob."
    exit 1

}

TARGETEXT='.jpg'

TARGETPREFIX='./' ## Make sure it ends with /.

while IFS= read -r FILE; do

    BASE=${FILE##*/}

    NOEXT=${BASE%.*}

    TARGETFILEPATH=${TARGETPREFIX}${NOEXT}${TARGETEXT}

    duration=$(ffprobe -i "$FILE" -show_format -v quiet | sed -n 's/duration=//p'| sed 's/\.[^\.]*$//')
    space=$(awk '{print $1/$2}' <<<"$duration 5")

       echo ffmpeg -ss "$space" -i "$FILE" -vf "select='isnan(prev_selected_t)+gte(t-prev_selected_t,"$space")',sca
le='if(gt(a,4/3),206,-1):if(gt(a,4/3),-1,154)',pad=w=206:h=155:x=(ow-iw)/2:y=(oh-ih)/2:color=black,tile=4x1" -aspect
 4:3 -frames:v 1 -vsync vfr "$TARGETFILEPATH" -y

done < <(exec find -type f -name '*.mp4')
</code>```

I have 2 mp4 files in the directory. If I run this code it work fine with 'echo' in front of the ffmpeg command. It'll output 2 lines of ffmpeg, one line for each file. Filenames are correct and all looks perfect.

When I run the same, removing 'echo', the first ffmpeg command will run successfully and my script will give an error for the 2nd file name. I can see in the ffmpeg output that there is one character missing at the beginning of the filename(should be uscenes.mp4).

```<code>scenes.mp4: No such file or directory
</code>```

答:
I've started over with a for loop and without find. All working now!

```<code>IEXT='.jpg'
for fname in ./*.mp4; do

    [ -e "$fname" ] || continue

    NOEXT=${fname::-4}
        OUPUT=${NOEXT}${IEXT}

        duration=$(ffprobe -i "$fname" -show_format -v quiet | sed -n 's/duration=//p'| sed 's/\.[^\.]*$//')
        space=$(awk '{print $1/$2}' <<<"$duration 5")

ffmpeg -ss "$space" -i "$fname" -vf "select='isnan(prev_selected_t)+gte(t-prev_selected_t,"$space")',scale='
if(gt(a,4/3),206,-1):if(gt(a,4/3),-1,154)',pad=w=206:h=155:x=(ow-iw)/2:y=(oh-ih)/2:color=black,tile=4x1" -aspect 4:3
 -frames:v 1 -vsync vfr "$OUPUT" -y

done
</code>```

Body:
Why is my code below not working as expected?

shopt -s extglob || {

    echo "Unable to enable exglob."
    exit 1

}

TARGETEXT='.jpg'

TARGETPREFIX='./' ## Make sure it ends with /.

while IFS= read -r FILE; do

    BASE=${FILE##*/}

    NOEXT=${BASE%.*}

    TARGETFILEPATH=${TARGETPREFIX}${NOEXT}${TARGETEXT}

    duration=$(ffprobe -i "$FILE" -show_format -v quiet | sed -n 's/duration=//p'| sed 's/\.[^\.]*$//')
    space=$(awk '{print $1/$2}' <<<"$duration 5")

       echo ffmpeg -ss "$space" -i "$FILE" -vf "select='isnan(prev_selected_t)+gte(t-prev_selected_t,"$space")',sca
le='if(gt(a,4/3),206,-1):if(gt(a,4/3),-1,154)',pad=w=206:h=155:x=(ow-iw)/2:y=(oh-ih)/2:color=black,tile=4x1" -aspect
 4:3 -frames:v 1 -vsync vfr "$TARGETFILEPATH" -y

done < <(exec find -type f -name '*.mp4')

I have 2 mp4 files in the directory. If I run this code it work fine with 'echo' in front of the ffmpeg command. It'll output 2 lines of ffmpeg, one line for each file. Filenames are correct and all looks perfect.

When I run the same, removing 'echo', the first ffmpeg command will run successfully and my script will give an error for the 2nd file name. I can see in the ffmpeg output that there is one character missing at the beginning of the filename(should be uscenes.mp4).

scenes.mp4: No such file or directory

Body:
I've started over with a for loop and without find. All working now!

IEXT='.jpg'
for fname in ./*.mp4; do

    [ -e "$fname" ] || continue

    NOEXT=${fname::-4}
        OUPUT=${NOEXT}${IEXT}

        duration=$(ffprobe -i "$fname" -show_format -v quiet | sed -n 's/duration=//p'| sed 's/\.[^\.]*$//')
        space=$(awk '{print $1/$2}' <<<"$duration 5")

ffmpeg -ss "$space" -i "$fname" -vf "select='isnan(prev_selected_t)+gte(t-prev_selected_t,"$space")',scale='
if(gt(a,4/3),206,-1):if(gt(a,4/3),-1,154)',pad=w=206:h=155:x=(ow-iw)/2:y=(oh-ih)/2:color=black,tile=4x1" -aspect 4:3
 -frames:v 1 -vsync vfr "$OUPUT" -y

done


问:
performance issue, edit distance for large strings LCP vs Levenshtein vs SIFT
So I'm trying to calculate the distance between two large strings (about 20-100).
The obstacle is the performance, I need to run 20k distance comparisons. (It takes hours)

After investigating, I came a cross few algorithms, And I'm having trouble to decide which to choose. (based on performance VS accuracy)

https://github.com/tdebatty/java-string-similarity - performance list for each of the algorithms.

** EDITED **

Is SIFT4 algorithm well-proven / reliable?

Is SIFT4 the right algorithm for the task?

How come it's so much faster than LCP-based / Levenshtein algorithm?

Is SIFT also used in image processing? or is it a different thing? answered by AMH

Thanks.

答:
As far as i know Scale-invariant feature transform (SIFT) is an algorithm in computer vision detect and describe local features in images.

also if you want to find similar images you must compare local features of images to each other by calculating their distance which may do what you intend to do. but local features are vector of numbers as i remember. it uses Brute-Force matcher:Feature Matching - OpenCV Library - SIFT

please read about SIFT here: http://docs.opencv.org/3.1.0/da/df5/tutorial_py_sift_intro.html

SIFT4 which is mentioned on your provided link is completely different thing.


问:
Appending the datetime to the end of every line in a 600 million row file
I have a 680 million rows (19gig) file that I need the datetime appended onto every line. I get this file every night and I have to add the time that I processed it to the end of each line. I have tried many ways to do this including sed/awk and loading it into a SQL database with the last column being defaulted to the current timestamp.

I was wondering if there is a fast way to do this? My fastest way so far takes two hours and that is just not fast enough given the urgency of the information in this file.  It is a flat CSV file.

edit1:

Here's what I've done so far:

```<code>awk -v date="$(date +"%Y-%m-%d %r")" '{ print $0","date}' lrn.ae.txt > testoutput.txt
</code>```

Time = 117 minutes

```<code>perl -ne 'chomp; printf "%s.pdf\n", $_' EXPORT.txt > testoutput.txt
</code>```

Time = 135 minutes

```<code>mysql load data local infile '/tmp/input.txt' into table testoutput
</code>```

Time = 211 minutes

答:
A solution that simplifies mjuarez' helpful approach:

```<code>yes "$(date +"%Y-%m-%d %r")" | paste -d',' file - | head -n "$(wc -l < file)" > out-file
</code>```

Note that, as with the approach in the linked answer, you must know the number of input lines in advance - here I'm using wc -l to count them, but if the number is fixed, simply use that fixed number.

yes keeps repeating its argument indefinitely, each on its own output line, until it is terminated.

paste -d',' file - pastes a corresponding pair of lines from file and stdin (-) on a single output line, separated with ,

Since yes produces "endless" output, head -n "$(wc -l < file)" ensures that processing stops once all input lines have been processed.

The use of a pipeline acts as a memory throttle, so running out of memory shouldn't be a concern.

Body:
I have a 680 million rows (19gig) file that I need the datetime appended onto every line. I get this file every night and I have to add the time that I processed it to the end of each line. I have tried many ways to do this including sed/awk and loading it into a SQL database with the last column being defaulted to the current timestamp.

I was wondering if there is a fast way to do this? My fastest way so far takes two hours and that is just not fast enough given the urgency of the information in this file.  It is a flat CSV file.

edit1:

Here's what I've done so far:

awk -v date="$(date +"%Y-%m-%d %r")" '{ print $0","date}' lrn.ae.txt > testoutput.txt

Time = 117 minutes

perl -ne 'chomp; printf "%s.pdf\n", $_' EXPORT.txt > testoutput.txt

Time = 135 minutes

mysql load data local infile '/tmp/input.txt' into table testoutput

Time = 211 minutes

Body:
A solution that simplifies mjuarez' helpful approach:

yes "$(date +"%Y-%m-%d %r")" | paste -d',' file - | head -n "$(wc -l < file)" > out-file

Note that, as with the approach in the linked answer, you must know the number of input lines in advance - here I'm using wc -l to count them, but if the number is fixed, simply use that fixed number.

yes keeps repeating its argument indefinitely, each on its own output line, until it is terminated.

paste -d',' file - pastes a corresponding pair of lines from file and stdin (-) on a single output line, separated with ,

Since yes produces "endless" output, head -n "$(wc -l < file)" ensures that processing stops once all input lines have been processed.

The use of a pipeline acts as a memory throttle, so running out of memory shouldn't be a concern.


问:
ReactJS this.state null
Let me preface this by saying I am a novice to ReactJS. I am trying to learn by making a simple site that populates data using React. I have a JSON file that contains link data that will be looped through with map.

I have tried setting it as the components state then passing it to the navbar links via a prop but I am getting "Uncaught TypeError: Cannot read property 'data' of null"

I tried to look around for solutions but could not find anything.

Note: When I try to hard code an object and map through it that way it returns map is undefined. However I am not sure that is directly related to the setState error.

```<code>/** @jsx React.DOM */

var conf = {
    companyName: "Slant Hosting"
  };

var NavbarLinks = React.createClass({
  render: function(){
    var navLinks = this.props.data.map(function(link){
      return(
        <li><a href={link.target}>{link.text}</a></li>
      );
    });
    return(
      <ul className="nav navbar-nav">
        {navLinks}
      </ul>
    )
  }
});

var NavbarBrand = React.createClass({
  render: function(){
    return(
      <a className="navbar-brand" href="#">{conf.companyName}</a>
    );
  }
});

var Navbar = React.createClass({
  getInitalState: function(){
    return{
      data : []
    };
  },
  loadNavbarJSON: function() {
    $.ajax({
      url: "app/js/configs/navbar.json",
      dataType: 'json',
      success: function(data) {
        this.setState({
          data: data
        });
        console.log(data);
        console.log(this.state.data);
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  componentDidMount: function(){
    this.loadNavbarJSON();
  },
  render: function(){
    return(
      <nav className="navbar navbar-default navbar-fixed-top" role="navigation">
        <div className="container-fluid">
          <div className="navbar-header">
            <NavbarBrand />
          </div>
          <NavbarLinks data={this.state.data} />
        </div>
      </nav>
    );
  }
});

var Header = React.createClass({
  render: function(){
    return(
      <Navbar />
    );
  }
});

React.renderComponent(
  <Header />,
  document.getElementById('render')
);
</code>```

答:
This question has already been answered, but I came here by having a problem that can easily happen to anyone.

I was getting a console.log(this.state) to log null in one of my methods, just because I didn't write:

this.handleSelect = this.handleSelect.bind(this);

in my constructor.

So, if you're getting a null for this.state in one of your methods, check if you have bounded it to your component.

Cheers!

Edit (because of @tutiplain's question)

Why was I getting null for this.state?

Because I wrote console.log(this.state) in the method which wasn't bounded to my class (my handleSelect method). That caused this to point to some object higher in the object hierarchy (most probably the window object) which doesn't have a property named state. So, by binding my handleSelect method to this, I assured that whenever I write this in that method, it will point to the object in which the method is in.

I encourage you to read a really good explanation for this here.

Title: ReactJS this.state null

Body:
Let me preface this by saying I am a novice to ReactJS. I am trying to learn by making a simple site that populates data using React. I have a JSON file that contains link data that will be looped through with map.

I have tried setting it as the components state then passing it to the navbar links via a prop but I am getting "Uncaught TypeError: Cannot read property 'data' of null"

I tried to look around for solutions but could not find anything.

Note: When I try to hard code an object and map through it that way it returns map is undefined. However I am not sure that is directly related to the setState error.

/** @jsx React.DOM */

var conf = {
    companyName: "Slant Hosting"
  };

var NavbarLinks = React.createClass({
  render: function(){
    var navLinks = this.props.data.map(function(link){
      return(

{link.text}

      );
    });
    return(

        {navLinks}

    )
  }
});

var NavbarBrand = React.createClass({
  render: function(){
    return(
      {conf.companyName}
    );
  }
});

var Navbar = React.createClass({
  getInitalState: function(){
    return{
      data : []
    };
  },
  loadNavbarJSON: function() {
    $.ajax({
      url: "app/js/configs/navbar.json",
      dataType: 'json',
      success: function(data) {
        this.setState({
          data: data
        });
        console.log(data);
        console.log(this.state.data);
      }.bind(this),
      error: function(xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
  componentDidMount: function(){
    this.loadNavbarJSON();
  },
  render: function(){
    return(

            <NavbarBrand />

          <NavbarLinks data={this.state.data} />

    );
  }
});

var Header = React.createClass({
  render: function(){
    return(
      <Navbar />
    );
  }
});

React.renderComponent(
  ,
  document.getElementById('render')
);


问:
SharedPreferences Logout not working
I have 2 Activities, Authentication and Mainpage.

In Authentication, it checks if the user is logged in, if the user is logged in, redirect it to Mainpage.class. This is how Authentication checks if the user is logged in and redirect it.

```<code>SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
boolean isLoggedIn = blockSession.getBoolean("logged_in", false);
if(isLoggedIn){
    Intent intent = new Intent(this, Mainpage.class);
    startActivity(intent);
}
</code>```

In Mainpage, I have a button which is a logout button and onClick event it use the logOut function that I've created. This is how logout button works:

```<code>void logOut(){
    SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
    SharedPreferences.Editor blockEdit = blockSession.edit();
    blockEdit.clear();
    blockEdit.apply();
    finish();

    Intent intent = new Intent(Mainpage.this, Authentication.class);
    startActivity(intent);
}
</code>```

The problem here is when I click the logout button, I just kept redirecting to Mainpage.

答:
Just reset your SharedPreferences KEY logged_in value to false using blockEdit.putBoolean("logged_in", false) and commit.

Try this:

```<code>void logOut(View view) {

    SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
    SharedPreferences.Editor blockEdit = blockSession.edit();

    // Set logged_in value to false
    blockEdit.putBoolean("logged_in", false);
    blockEdit.commit();

    // Start Authentication
    Intent intent = new Intent(Mainpage.this, Authentication.class);
    startActivity(intent);

    // Finish MainPage
    finish();
}
</code>```

#. Best practice is to create a common class for session management and use this from anywhere in your application as per your needs.

Crate a SessionManager class like below:

```<code>public class SessionManager {

    // LogCat tag
    private static String TAG = SessionManager.class.getSimpleName();

    Context context;

    // Shared Preferences
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;

    // Shared pref mode
    int PRIVATE_MODE = 0;

    // Shared preferences file name
    private static final String PREF_NAME = "MY_APP";

    private static final String KEY_IS_LOGGED_IN = "IS_LOGGED_IN";

    private static final String KEY_USER_ID = "USER_ID";
    private static final String KEY_USER_EMAIL = "USER_EMAIL";
    private static final String KEY_USER_USERNAME = "USER_USERNAME";

    public SessionManager(Context context) {
        this.context = context;
        sharedPreferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = sharedPreferences.edit();
    }

    public void setLogin(boolean isLoggedIn) {

        editor.putBoolean(KEY_IS_LOGGED_IN, isLoggedIn);

        // commit changes
        editor.commit();

        Log.d(TAG, "User login session modified!");
    }

    public boolean isLoggedIn() {
        return sharedPreferences.getBoolean(KEY_IS_LOGGED_IN, false);
    }

    public void setUserId(int id) {
        editor.putInt(KEY_USER_ID, id);
        editor.commit();
    }

    public int getUserId() {
        return sharedPreferences.getInt(KEY_USER_ID, 0);
    }

    public void setUsername(String username) {
        editor.putString(KEY_USER_USERNAME, username);
        editor.commit();
    }

    public String getUsername() {
        return sharedPreferences.getString(KEY_USER_USERNAME, "user1234");
    }

    public void setEmail(String email) {
        editor.putString(KEY_USER_EMAIL, email);
        editor.commit();
    }

    public String getEmail() {
        return sharedPreferences.getString(KEY_USER_EMAIL, "default@gmail.com");
    }
}
</code>```

USE:

LOGIN:

```<code>SessionManager sessionManager = new SessionManager(getApplicationContext());
sessionManager.setLogin(true);
sessionManager.setUserId(userId);

// Launch MainPage
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
</code>```

LOGOUT:

```<code>SessionManager sessionManager = new SessionManager(getApplicationContext());
sessionManager.setLogin(false);

// Launch LoginPage
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
</code>```

Hope this will help~

Title: SharedPreferences Logout not working

Body:
I have 2 Activities, Authentication and Mainpage.

In Authentication, it checks if the user is logged in, if the user is logged in, redirect it to Mainpage.class. This is how Authentication checks if the user is logged in and redirect it.

SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
boolean isLoggedIn = blockSession.getBoolean("logged_in", false);
if(isLoggedIn){
    Intent intent = new Intent(this, Mainpage.class);
    startActivity(intent);
}

In Mainpage, I have a button which is a logout button and onClick event it use the logOut function that I've created. This is how logout button works:

void logOut(){
    SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
    SharedPreferences.Editor blockEdit = blockSession.edit();
    blockEdit.clear();
    blockEdit.apply();
    finish();

    Intent intent = new Intent(Mainpage.this, Authentication.class);
    startActivity(intent);
}

The problem here is when I click the logout button, I just kept redirecting to Mainpage.

Body:
Just reset your SharedPreferences KEY logged_in value to false using blockEdit.putBoolean("logged_in", false) and commit.

Try this:

void logOut(View view) {

    SharedPreferences blockSession = this.getSharedPreferences("blockSession", 0);
    SharedPreferences.Editor blockEdit = blockSession.edit();

    // Set logged_in value to false
    blockEdit.putBoolean("logged_in", false);
    blockEdit.commit();

    // Start Authentication
    Intent intent = new Intent(Mainpage.this, Authentication.class);
    startActivity(intent);

    // Finish MainPage
    finish();
}

#. Best practice is to create a common class for session management and use this from anywhere in your application as per your needs.

Crate a SessionManager class like below:

public class SessionManager {

    // LogCat tag
    private static String TAG = SessionManager.class.getSimpleName();

    Context context;

    // Shared Preferences
    SharedPreferences sharedPreferences;
    SharedPreferences.Editor editor;

    // Shared pref mode
    int PRIVATE_MODE = 0;

    // Shared preferences file name
    private static final String PREF_NAME = "MY_APP";

    private static final String KEY_IS_LOGGED_IN = "IS_LOGGED_IN";

    private static final String KEY_USER_ID = "USER_ID";
    private static final String KEY_USER_EMAIL = "USER_EMAIL";
    private static final String KEY_USER_USERNAME = "USER_USERNAME";

    public SessionManager(Context context) {
        this.context = context;
        sharedPreferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
        editor = sharedPreferences.edit();
    }

    public void setLogin(boolean isLoggedIn) {

        editor.putBoolean(KEY_IS_LOGGED_IN, isLoggedIn);

        // commit changes
        editor.commit();

        Log.d(TAG, "User login session modified!");
    }

    public boolean isLoggedIn() {
        return sharedPreferences.getBoolean(KEY_IS_LOGGED_IN, false);
    }

    public void setUserId(int id) {
        editor.putInt(KEY_USER_ID, id);
        editor.commit();
    }

    public int getUserId() {
        return sharedPreferences.getInt(KEY_USER_ID, 0);
    }

    public void setUsername(String username) {
        editor.putString(KEY_USER_USERNAME, username);
        editor.commit();
    }

    public String getUsername() {
        return sharedPreferences.getString(KEY_USER_USERNAME, "user1234");
    }

    public void setEmail(String email) {
        editor.putString(KEY_USER_EMAIL, email);
        editor.commit();
    }

    public String getEmail() {
        return sharedPreferences.getString(KEY_USER_EMAIL, "default@gmail.com");
    }
}

USE:

LOGIN:

SessionManager sessionManager = new SessionManager(getApplicationContext());
sessionManager.setLogin(true);
sessionManager.setUserId(userId);

// Launch MainPage
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();

LOGOUT:

SessionManager sessionManager = new SessionManager(getApplicationContext());
sessionManager.setLogin(false);

// Launch LoginPage
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();

Hope this will help~