问:
How to make highcharts scrollable horizontally when having big range in x-axis
I am generating my x-axis and y-axis data dynamically and displaying highcharts, but the chart becomes messy when the x-axis range is high with small intervals.

How do I make highcharts to make normal horizontally scrollable graph?

Here is what I am using right now:

```<code><div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>

//CODE FOR HIGHCHARTS JS
function makeChart() {
    $('#container').highcharts({
        chart: {
            type: 'line',
            marginRight: 130,
            marginBottom: 100
        },
        title: {
            text: 'Banana',
            x: -20 //center
        },
        subtitle: {
            text: 'Source: banana.com',
            x: -20
        },
        xAxis: {
            categories: xlist
        },
        yAxis: {
            title: {
                text: 'No. of C'
            },
            plotLines: [{
                value: 0,
                width: 1,
                color: '#808080'
            }]
        },
        tooltip: {
            valueSuffix: 'C'
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'top',
            x: -10,
            y: 100,
            borderWidth: 0
        },
        series: [{
            name: $("#repoSelector option:selected").text(),
            data: ylist
        }]
    });
}
</code>```

答:
To enable scrollbar in x-axis, try this

```<code>xAxis: {
  categories: xlist,
  min: 0,
  max: 4,
  scrollbar: {
        enabled: true
  },
  },
</code>```

Check the jfiddle here: https://jsfiddle.net/BhavyaAprajita/zja90wf2/1/

Also, make sure that you import the highstock library

```<code>src="https://code.highcharts.com/stock/highstock.js"
</code>```

Body:
I am generating my x-axis and y-axis data dynamically and displaying highcharts, but the chart becomes messy when the x-axis range is high with small intervals.

How do I make highcharts to make normal horizontally scrollable graph?

Here is what I am using right now:

//CODE FOR HIGHCHARTS JS
function makeChart() {
    $('#container').highcharts({
        chart: {
            type: 'line',
            marginRight: 130,
            marginBottom: 100
        },
        title: {
            text: 'Banana',
            x: -20 //center
        },
        subtitle: {
            text: 'Source: banana.com',
            x: -20
        },
        xAxis: {
            categories: xlist
        },
        yAxis: {
            title: {
                text: 'No. of C'
            },
            plotLines: [{
                value: 0,
                width: 1,
                color: '#808080'
            }]
        },
        tooltip: {
            valueSuffix: 'C'
        },
        legend: {
            layout: 'vertical',
            align: 'right',
            verticalAlign: 'top',
            x: -10,
            y: 100,
            borderWidth: 0
        },
        series: [{
            name: $("#repoSelector option:selected").text(),
            data: ylist
        }]
    });
}

Body:
To enable scrollbar in x-axis, try this

xAxis: {
  categories: xlist,
  min: 0,
  max: 4,
  scrollbar: {
        enabled: true
  },
  },

Check the jfiddle here: https://jsfiddle.net/BhavyaAprajita/zja90wf2/1/

Also, make sure that you import the highstock library

src="https://code.highcharts.com/stock/highstock.js"


来源: stackexchange

问:
C Multidimensional Array: Am I missing something?
I'm currently learning C, and I have just written a draft of a program that allows a user to move a player around a character-based maze/path. I have built the maze/path as multidimensional character array, with a while loop controlling the player's position by replacing certain characters in the array. Here is the multidimensional array I have initialised:

```<code>char maze[5][7] = {
    {"_", "_", "_", "_", "_"},
    {"|", " ", " ", " ", "|"},
    {"|", " ", "|", " ", "|"},
    {"|", " ", "|", "_", "|"},
    {"|", "_", " ", " ", "|"},
    {"|", " ", "|", " ", "|"},
    {"|", "_", "_", "_", "|"}
};
</code>```

However, when I try to compile, I get this error:

```<code>error: '}' expected
</code>```

The first row in the array is apparently missing some sort of closing bracket, although I have checked proper array syntax multiple times and this appears to be correct. What am I missing? Are there any other issues with this?

答:
Your array is of type char, but your entries are of type char *. Replace double quotes " with single quotes '.

Single quotes represent char itself where double quotes represent char sequence (string) therefore compiler will try to add \0 character to the end.

On the other hand, you have to swap values 5 and 7 for initialization.

End result is similar to this:

```<code>//7 big entries with 5 values
char maze[7][5] = {
    {'_', '_', '_', '_', '_'},
    {'_', '_', '_', '_', '_'},
    {'_', '_', '_', '_', '_'},
    {'_', '_', '_', '_', '_'},
    {'_', '_', '_', '_', '_'},
    {'_', '_', '_', '_', '_'},
    {'_', '_', '_', '_', '_'},
};
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm currently learning C, and I have just written a draft of a program that allows a user to move a player around a character-based maze/path. I have built the maze/path as multidimensional character array, with a while loop controlling the player's position by replacing certain characters in the array. Here is the multidimensional array I have initialised:

char maze[5][7] = {
    {"_", "_", "_", "_", "_"},
    {"|", " ", " ", " ", "|"},
    {"|", " ", "|", " ", "|"},
    {"|", " ", "|", "_", "|"},
    {"|", "_", " ", " ", "|"},
    {"|", " ", "|", " ", "|"},
    {"|", "_", "_", "_", "|"}
};

However, when I try to compile, I get this error:

error: '}' expected

The first row in the array is apparently missing some sort of closing bracket, although I have checked proper array syntax multiple times and this appears to be correct. What am I missing? Are there any other issues with this?

Body:
Your array is of type char, but your entries are of type char *. Replace double quotes " with single quotes '.

Single quotes represent char itself where double quotes represent char sequence (string) therefore compiler will try to add \0 character to the end.

On the other hand, you have to swap values 5 and 7 for initialization.

End result is similar to this:

//7 big entries with 5 values
char maze[7][5] = {
    {'_', '_', '_', '_', '_'},
    {'_', '_', '_', '_', '_'},
    {'_', '_', '_', '_', '_'},
    {'_', '_', '_', '_', '_'},
    {'_', '_', '_', '_', '_'},
    {'_', '_', '_', '_', '_'},
    {'_', '_', '_', '_', '_'},
};


问:
Group Artists in Deezer by tags
Does Deezer have any way to group list of artist by tags, category, custom user comment or other way?

I have long list of Artist and want to group (or order) them by my own custom parameters (for example, by style, by music type, etc). I know that I can create custom playlists, but in playlist I can add only single songs, not the whole artist.

Is there any solution for this task - group/filter artist list by custom user tags?

答: You can use the "genre" endpoint available here: http://developers.deezer.com/api/genre#connections. You can retrieve the artists by genre, or podcasts and radios if you want.</p>

Title: Group Artists in Deezer by tags


问:
Create a list of repeated consecutive numbers regarding number from another list
I want to create a list with repeated consecutive numbers from zero regarding numbers from list1

```<code>list1 = [3,5,4,1,2,2]
</code>```

Expected list should have 3 zeros, 5 ones, 4 twos, and so on.

```<code>list2 = [0,0,0,1,1,1,1,1,2,2,2,2,3,4,4,5,5]
</code>```

答:
You can do this with a list comprehension, but it's a little more efficient to use a traditional for loop and the .extend method.

```<code>list1 = [3,5,4,1,2,2]
list2 = []
for i, v in enumerate(list1):
    list2.extend([i] * v)
print(list2)
</code>```

output

```<code>[0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 4, 4, 5, 5]
</code>```

Another option is to use itertools.chain:

```<code>list2 = list(chain.from_iterable([i] * v for i, v in enumerate(list1)))
</code>```

or, the slightly shorter, but more cryptic

```<code>list2 = list(chain(*([i] * v for i, v in enumerate(list1))))
</code>```

Body:
I want to create a list with repeated consecutive numbers from zero regarding numbers from list1

list1 = [3,5,4,1,2,2]

Expected list should have 3 zeros, 5 ones, 4 twos, and so on.

list2 = [0,0,0,1,1,1,1,1,2,2,2,2,3,4,4,5,5]

Body:
You can do this with a list comprehension, but it's a little more efficient to use a traditional for loop and the .extend method.

list1 = [3,5,4,1,2,2]
list2 = []
for i, v in enumerate(list1):
    list2.extend([i] * v)
print(list2)

output

[0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 4, 4, 5, 5]

Another option is to use itertools.chain:

list2 = list(chain.from_iterable([i] * v for i, v in enumerate(list1)))

or, the slightly shorter, but more cryptic

list2 = list(chain(*([i] * v for i, v in enumerate(list1))))


问:
How to create a date range with php?
I tried to make time with PHP. start date of 2017-01-29 to 2017-12-29. But that happened I could not print in February because the month maximum of only 28 days. How to order printed anyway but with the February date up to 28.

my script:

```<code>date_default_timezone_set('UTC');

// Start date
$date = '2017-01-29';
// End date
$end_date = '2017-12-29';

while (strtotime($date) <= strtotime($end_date)) {
    echo "$date\n";
    echo "<br>";
    $date = date ("Y-m-d", strtotime("+1 month", strtotime($date)));
}
</code>```

Output:

答:
Another approach you can try where you don't have to use DateTime.

```<code>    date_default_timezone_set('UTC');

    // Start date
    $date = '2017-01-29';
    // End date
    $end_date = '2017-12-29';

    while (strtotime($date) <= strtotime($end_date)) {
        echo "$date\n";
        echo "<br>";
        $date = date("Y-m-t", strtotime("+30 day", strtotime($date)));
    }
</code>```

Using strtotime("+30 day", strtotime($date), you can add 30 days to the current date and get the last date of the month with t.

```<code>    2017-01-29
    2017-02-28
    2017-03-31
    2017-04-30
    2017-05-31
    2017-06-30
    2017-07-31
    2017-08-31
    2017-09-30
    2017-10-31
    2017-11-30
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to create a date range with php?

Body:
I tried to make time with PHP. start date of 2017-01-29 to 2017-12-29. But that happened I could not print in February because the month maximum of only 28 days. How to order printed anyway but with the February date up to 28.

my script:

date_default_timezone_set('UTC');

// Start date
$date = '2017-01-29';
// End date
$end_date = '2017-12-29';

while (strtotime($date) <= strtotime($end_date)) {
    echo "$date\n";
    echo "
";
    $date = date ("Y-m-d", strtotime("+1 month", strtotime($date)));
}

Output:

Body:
Another approach you can try where you don't have to use DateTime.

    date_default_timezone_set('UTC');

    // Start date
    $date = '2017-01-29';
    // End date
    $end_date = '2017-12-29';

    while (strtotime($date) <= strtotime($end_date)) {
        echo "$date\n";
        echo "<br>";
        $date = date("Y-m-t", strtotime("+30 day", strtotime($date)));
    }

Using strtotime("+30 day", strtotime($date), you can add 30 days to the current date and get the last date of the month with t.

    2017-01-29
    2017-02-28
    2017-03-31
    2017-04-30
    2017-05-31
    2017-06-30
    2017-07-31
    2017-08-31
    2017-09-30
    2017-10-31
    2017-11-30


问:
Algorithm to always sum sliders to 100% failing due to zeroes
This is (supposed to be) a function which makes sure that the the sum of a number of slider's values always adds up to globalTotal.

A slider value can be changed manually by the user to changer.value and then when applying this function to the values of the other sliders, it can determine their new or endVal.

It takes the startVal of the slider which needs changing and the original value of the slider that changed changerStartVal and can determine the new value others by weighting.

The problem and my question is. Sometimes remainingStartVals can be zero (when the slider changing gets moved all the way to maximum) or startVal can be zero (when the slider changing is moved to zero and then another slider is moved). When this happens I get a divide-by-zero or a multiply-by-zero respectively. Both of which are bad and lead to incorrect results. Is there an easy way to fix this?

```<code>func calcNewVal(startVal: Float, changerStartVal: Float) -> Float {

    let remainingStartVals = globalTotal - changerStartVal

    let remainingNewVals = globalTotal - changer.value

    let endVal = ((startVal * (100 / remainingStartVals)) / 100) * remainingNewVals

    return endVal

}
</code>```

答:
Hey @Sean the simplest adjustment that I could think of here is to check if the remainingStartVals is not 0 that means that there are weights assigned to the other sliders and also check if a single slider had a weight to begin with which means its startVal shouldn't be equal to 0

```<code>func calcNewVal(startVal: Float, changerStartVal: Float) -> Float{
var endVal = 0
let remainingStartVals = globalTotal - changerStartVal
if remainingStartVals != 0 || startVal != 0{
    let remainingNewVals = globalTotal - changer.value
    endVal = ((startVal * (100 / remainingStartVals)) / 100) * remainingNewVals
}
return endVal
</code>```

}

Body:
This is (supposed to be) a function which makes sure that the the sum of a number of slider's values always adds up to globalTotal.

A slider value can be changed manually by the user to changer.value and then when applying this function to the values of the other sliders, it can determine their new or endVal.

It takes the startVal of the slider which needs changing and the original value of the slider that changed changerStartVal and can determine the new value others by weighting.

The problem and my question is. Sometimes remainingStartVals can be zero (when the slider changing gets moved all the way to maximum) or startVal can be zero (when the slider changing is moved to zero and then another slider is moved). When this happens I get a divide-by-zero or a multiply-by-zero respectively. Both of which are bad and lead to incorrect results. Is there an easy way to fix this?

func calcNewVal(startVal: Float, changerStartVal: Float) -> Float {

    let remainingStartVals = globalTotal - changerStartVal

    let remainingNewVals = globalTotal - changer.value

    let endVal = ((startVal * (100 / remainingStartVals)) / 100) * remainingNewVals

    return endVal

}

Body:
Hey @Sean the simplest adjustment that I could think of here is to check if the remainingStartVals is not 0 that means that there are weights assigned to the other sliders and also check if a single slider had a weight to begin with which means its startVal shouldn't be equal to 0

func calcNewVal(startVal: Float, changerStartVal: Float) -> Float{
var endVal = 0
let remainingStartVals = globalTotal - changerStartVal
if remainingStartVals != 0 || startVal != 0{
    let remainingNewVals = globalTotal - changer.value
    endVal = ((startVal * (100 / remainingStartVals)) / 100) * remainingNewVals
}
return endVal

}


问:
Autolayouts not working as expected in iPhone 6s Plus
I have

UIImageviewUIView - The Background image

UIView - being treated as a gradient layer on top of the image.

Here the constraints given for the gradient view is

Align top and leading to the UIImageView

Equal height and Width as
the UIImageView

These are working perfectly on iPhone 5s, 6s but fails to work on iPhone 6s Plus. The gradient view doesnt cover the UIImageView fully.
Attaching a sample image

P.S I already unchecked Constraint to margin in Interface Builder. Still not working.
Can anyone help me with what i am missing?

答: Try these constraints on imageView and the other view on top of it:


问:
Start script when new element on directory
I want to convert every new wav file coming into an input dir to another dir on mp3. I've been look how to convert those file but, I don't know how to add a listener on the input dir or if it's even possible?

Edit:
Sorry, I've forget to share you the code I already have. I use ffmpeg to convert audio file

```<code>import os, sys, glob

FFMPEG_PATH = "C:\\ffmpeg\\bin"

fileName = ""
fileExt = ""

wavdir = ""
mp3dir = ""

for file in glob.glob('wav/*.wav'):

    # get the name  without .ext
    fileName = os.path.basename(file)
    fileName = fileName.split(".")[0]

    # verify if no mp3 file with thesame name exist
    if not os.path.isfile('./mp3/'+fileName+".mp3"):

        # set var with the 2 types files dir
        wavdir = file
        mp3dir = "mp3/"+fileName+".mp3"

        # start the convertion with ffmpeg by commande line
        os.system("ffmpeg -i "+wavdir+" "+mp3dir)
</code>```

答:
I'm not sure if this is the best idea, however you can assign a process or a thread to check if a file was added to the directory every X seconds:</p>

```<code>import os
import time
wav_files_path = "/WAV_dir_path"
prev_files = os.listdir(wav_files_path)
x = 1 # time to sleep
while True:
    files = os.listdir(wav_files_path)
    if len(files) > len(prev_files):  # if files are not deleted it's better to check if any files were added
        # NEW FILE(S) ADDED
        for f in files:
            if f not in prev_files:
                convert_file(f)
    prev_files = files
    time.sleep(x)
</code>```

Body:
I want to convert every new wav file coming into an input dir to another dir on mp3. I've been look how to convert those file but, I don't know how to add a listener on the input dir or if it's even possible?

Edit:
Sorry, I've forget to share you the code I already have. I use ffmpeg to convert audio file

import os, sys, glob

FFMPEG_PATH = "C:\\ffmpeg\\bin"

fileName = ""
fileExt = ""

wavdir = ""
mp3dir = ""

for file in glob.glob('wav/*.wav'):

    # get the name  without .ext
    fileName = os.path.basename(file)
    fileName = fileName.split(".")[0]

    # verify if no mp3 file with thesame name exist
    if not os.path.isfile('./mp3/'+fileName+".mp3"):

        # set var with the 2 types files dir
        wavdir = file
        mp3dir = "mp3/"+fileName+".mp3"

        # start the convertion with ffmpeg by commande line
        os.system("ffmpeg -i "+wavdir+" "+mp3dir)

Body:
I'm not sure if this is the best idea, however you can assign a process or a thread to check if a file was added to the directory every X seconds:

import os
import time
wav_files_path = "/WAV_dir_path"
prev_files = os.listdir(wav_files_path)
x = 1 # time to sleep
while True:
    files = os.listdir(wav_files_path)
    if len(files) > len(prev_files):  # if files are not deleted it's better to check if any files were added
        # NEW FILE(S) ADDED
        for f in files:
            if f not in prev_files:
                convert_file(f)
    prev_files = files
    time.sleep(x)


问:
Create PDF file from PHP
I am trying to create an PDF file from a PHP page with jsPDF but it is not working and I dont know whats wrong.

Can someone help me?

First I have a Iframe. The page I want to convert is displayed in the Iframe:

Iframe:

```<code><?php
    <iframe id="frame" name="frame" width="100%" height="1160px" frameborder="0" src="./page.php?id=' . $_GET['id'] . '"></iframe>
    <button id="cmd">Button</button>
?>
</code>```

When I hit Button the following script should convert the page to PDF

Script

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
<script type="text/javascript">
    var doc = new jsPDF();

    var specialElementHandlers = {
        '#editor': function(element, renderer){
            return true;
        }
    };

    $('#cmd').click(function () {
        doc.fromHTML($('frame').get(0), 15, 15, {
            'width': 170,
            'elementHandlers': specialElementHandlers
        });

    doc.save('sample-file.pdf');
    });
</script>
</code>```

But when I hit Button. Nothing is happening. Does someone know whats wrong?

答:
You must be get html of iframe, so use contents() function and then get documentElement of iframe:

```<code><iframe id="frame" name="frame" width="100%" height="1160px" frameborder="0" src="http://localhost/"></iframe>
<button id="cmd">Button</button>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
<script type="text/javascript">
    var doc = new jsPDF();

    var specialElementHandlers = {
        '#editor': function(element, renderer){
            return true;
        }
    };

    $('#cmd').click(function () {
        doc.fromHTML($('#frame').contents().find('html').html(), 15, 15, {
            'width': 170,
            'elementHandlers': specialElementHandlers
        });

    doc.save('sample-file.pdf');
    });
</script>
</code>```

Note: If your iframe source page or part of it protected with x-frame-options header, you cannot access to html of it.

Title: Create PDF file from PHP

Body:
I am trying to create an PDF file from a PHP page with jsPDF but it is not working and I dont know whats wrong.

Can someone help me?

First I have a Iframe. The page I want to convert is displayed in the Iframe:

Iframe:

<?php

    <button id="cmd">Button</button>
?>

When I hit Button the following script should convert the page to PDF

Script

But when I hit Button. Nothing is happening. Does someone know whats wrong?

Body:
You must be get html of iframe, so use contents() function and then get documentElement of iframe:

<iframe id="frame" name="frame" width="100%" height="1160px" frameborder="0" src="http://localhost/"></iframe>
<button id="cmd">Button</button>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>
<script type="text/javascript">
    var doc = new jsPDF();

    var specialElementHandlers = {
        '#editor': function(element, renderer){
            return true;
        }
    };

    $('#cmd').click(function () {
        doc.fromHTML($('#frame').contents().find('html').html(), 15, 15, {
            'width': 170,
            'elementHandlers': specialElementHandlers
        });

    doc.save('sample-file.pdf');
    });
</script>

Note: If your iframe source page or part of it protected with x-frame-options header, you cannot access to html of it.


问:
How I can hide and show tabs conditionally - Ionic 2?
The case is the following: I have a ion-tabs container with several ion-tab elements, and different users that logs into my application. What I need to do is to show or hide the ion-tab elements depending on the user type logged.

The problem is that I need to do this dynamically, and if I use a directive like [show]="variable", it does not work.

tabs.ts

```<code>import { Component } from '@angular/core';

import { Page1 } from '../page1/page1';
import { Page2 } from '../page2/page2';

@Component({
  templateUrl: 'tabs.html'
})
export class TabsPage {
  // this tells the tabs component which Pages
  // should be each tab's root Page
  tab1Root: any;
  tab2Root: any;
  tab3Root: any;
  tab4Root: any;
  tab5Root: any;
  variable: any;

  constructor(public userData: UserData) {
   // get variable from local storage
    this.userData.getUser().then((value) => {
      if(value.typeLabel == 'Expert') {
        this.variable = true;
        console.log('1->',value.typeLabel);
      }else if(value.typeLabel == 'Client'){
        this.variable = false;
        console.log('2->',value.typeLabel);
      }
    });

    this.tab1Root = this.variable?Page1:Page2; <-- i want to show specify tabs depending on variable value
    this.tab2Root = NotificationsPage;
    this.tab3Root = MessagesPage;
    this.tab4Root = InstructionsPage;
    this.tab5Root = ExpertsPage;
  }
}
</code>```

tabs.html

```<code><ion-tabs>
  <ion-tab [root]="tab1Root" tabTitle="Home" tabIcon="home"></ion-tab>
  <ion-tab [root]="tab2Root" tabTitle="tab_title" tabIcon="notifications"></ion-tab>
  <ion-tab [root]="tab3Root" tabTitle="tab_title" tabIcon="home"></ion-tab>
  <ion-tab [root]="tab4Root" tabTitle="tab_title" tabIcon="home"></ion-tab>
  <ion-tab [root]="tab5Root" tabTitle="tab_title" tabIcon="home"></ion-tab>
</ion-tabs>
</code>```

But always this.tab1Root return Page1;

What am I doing wrong? Can somebody help me?

答:
As I answered in the ionic forum:
It just won't work. That's how Ionic is built, it currently does not allow for dynamically setting the tab root page. I had to hack around for some hours and finally got it to work in the following way:
1) Get the reference of the tabs component and the reference of the tab you want to set dynamically. Do not set the [root] attribute for this dynamical tab because Ionic will run a method that simply won't allow you to update the root page for this tab later.

```<code><ion-tabs #appTabs>
  <ion-tab #tabA tabTitle="Tab A" tabIcon="list-box"></ion-tab>
  <ion-tab [root]="tab2Root" tabTitle="Tab B" tabIcon="albums"></ion-tab>
  <ion-tab [root]="tab3Root" tabTitle="Tab C" tabIcon="pulse"></ion-tab>
  <ion-tab [root]="tab4Root" tabTitle="Tab D" tabIcon="more"></ion-tab>
</ion-tabs>
</code>```

2) In the TabsPage file:

```<code>import { Component, ViewChild } from '@angular/core';
import { Store } from '@ngrx/store'; // I'm using ngrx
import { Tabs, Tab } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';
import 'rxjs/operator/filter';
import 'rxjs/operator/map';

import { TabA1Page } from '...';
import { TabA2Page } from '...';
import { TabBPage } from '...';
import { TabCPage } from '...';
import { TabDPage } from '...';
import { AppState } from '../../app.reducer';
import { DashboardCard } from '...';

@Component({
  templateUrl: 'tabs.page.html',
  selector: 'page-tabs'
})
export class TabsPage {
  public tab1Root: any; // As you can see, it's not set yet.
  public tab2Root: any = TabBPage;
  public tab3Root: any = TabCPage;
  public tab4Root: any = TabDPage;

  // Get the references
  @ViewChild('appTabs') private tabsRef: Tabs;
  @ViewChild('tabA') private tabRef: Tab;

  constructor(private store: Store<AppState>) {}

  public ionViewDidEnter() {
    // These three sources can change the root page for the tab A:
    const defaultDashboard$ = this.store.select('task', 'fetchDashboardCards', 'value');
    const dashboardByProject$ = this.store.select('task', 'fetchDashboardCardsByProject', 'value');
    const dashboardByDueDate$ = this.store.select('task', 'fetchDashboardCardsByDueDate', 'value');

    Observable
      .merge(defaultDashboard$, dashboardByProject$, dashboardByDueDate$)
      .filter(v => v != null)
      .map((dashboard: DashboardCard[]) => dashboard[0].layout === 'project' ? TabA1 : TabA2)
      .distinctUntilChanged()
      .subscribe(this.setTabARootPage.bind(this));
  }

  private setTabARootPage(rootPage) {
    // This is the hack

    // set the root property that we didn't set in the view as [root]="..."
    this.tabRef.root = rootPage;

    /*
    * Modifying private attributes to make it work.
    * This will allow Ionic to run the "tabsInstance.load()" method to load a new root page
    * It also allows us to select the same tab again.
    */
    this.tabRef._loaded = false;
    this.tabsRef._tabs[0].isSelected = false;

    this.tabsRef.select(this.tabRef); // select the tab again
  }

}
</code>```

Body:
The case is the following: I have a ion-tabs container with several ion-tab elements, and different users that logs into my application. What I need to do is to show or hide the ion-tab elements depending on the user type logged.

The problem is that I need to do this dynamically, and if I use a directive like [show]="variable", it does not work.

tabs.ts

import { Component } from '@angular/core';

import { Page1 } from '../page1/page1';
import { Page2 } from '../page2/page2';

@Component({
  templateUrl: 'tabs.html'
})
export class TabsPage {
  // this tells the tabs component which Pages
  // should be each tab's root Page
  tab1Root: any;
  tab2Root: any;
  tab3Root: any;
  tab4Root: any;
  tab5Root: any;
  variable: any;

  constructor(public userData: UserData) {
   // get variable from local storage
    this.userData.getUser().then((value) => {
      if(value.typeLabel == 'Expert') {
        this.variable = true;
        console.log('1->',value.typeLabel);
      }else if(value.typeLabel == 'Client'){
        this.variable = false;
        console.log('2->',value.typeLabel);
      }
    });

    this.tab1Root = this.variable?Page1:Page2; <-- i want to show specify tabs depending on variable value
    this.tab2Root = NotificationsPage;
    this.tab3Root = MessagesPage;
    this.tab4Root = InstructionsPage;
    this.tab5Root = ExpertsPage;
  }
}

tabs.html

<ion-tabs>
  <ion-tab [root]="tab1Root" tabTitle="Home" tabIcon="home"></ion-tab>
  <ion-tab [root]="tab2Root" tabTitle="tab_title" tabIcon="notifications"></ion-tab>
  <ion-tab [root]="tab3Root" tabTitle="tab_title" tabIcon="home"></ion-tab>
  <ion-tab [root]="tab4Root" tabTitle="tab_title" tabIcon="home"></ion-tab>
  <ion-tab [root]="tab5Root" tabTitle="tab_title" tabIcon="home"></ion-tab>
</ion-tabs>

But always this.tab1Root return Page1;

What am I doing wrong? Can somebody help me?

Body:
As I answered in the ionic forum:
It just won't work. That's how Ionic is built, it currently does not allow for dynamically setting the tab root page. I had to hack around for some hours and finally got it to work in the following way:
1) Get the reference of the tabs component and the reference of the tab you want to set dynamically. Do not set the [root] attribute for this dynamical tab because Ionic will run a method that simply won't allow you to update the root page for this tab later.

<ion-tabs #appTabs>
  <ion-tab #tabA tabTitle="Tab A" tabIcon="list-box"></ion-tab>
  <ion-tab [root]="tab2Root" tabTitle="Tab B" tabIcon="albums"></ion-tab>
  <ion-tab [root]="tab3Root" tabTitle="Tab C" tabIcon="pulse"></ion-tab>
  <ion-tab [root]="tab4Root" tabTitle="Tab D" tabIcon="more"></ion-tab>
</ion-tabs>

2) In the TabsPage file:

import { Component, ViewChild } from '@angular/core';
import { Store } from '@ngrx/store'; // I'm using ngrx
import { Tabs, Tab } from 'ionic-angular';
import { Observable } from 'rxjs/Observable';
import 'rxjs/operator/filter';
import 'rxjs/operator/map';

import { TabA1Page } from '...';
import { TabA2Page } from '...';
import { TabBPage } from '...';
import { TabCPage } from '...';
import { TabDPage } from '...';
import { AppState } from '../../app.reducer';
import { DashboardCard } from '...';

@Component({
  templateUrl: 'tabs.page.html',
  selector: 'page-tabs'
})
export class TabsPage {
  public tab1Root: any; // As you can see, it's not set yet.
  public tab2Root: any = TabBPage;
  public tab3Root: any = TabCPage;
  public tab4Root: any = TabDPage;

  // Get the references
  @ViewChild('appTabs') private tabsRef: Tabs;
  @ViewChild('tabA') private tabRef: Tab;

  constructor(private store: Store<AppState>) {}

  public ionViewDidEnter() {
    // These three sources can change the root page for the tab A:
    const defaultDashboard$ = this.store.select('task', 'fetchDashboardCards', 'value');
    const dashboardByProject$ = this.store.select('task', 'fetchDashboardCardsByProject', 'value');
    const dashboardByDueDate$ = this.store.select('task', 'fetchDashboardCardsByDueDate', 'value');

    Observable
      .merge(defaultDashboard$, dashboardByProject$, dashboardByDueDate$)
      .filter(v => v != null)
      .map((dashboard: DashboardCard[]) => dashboard[0].layout === 'project' ? TabA1 : TabA2)
      .distinctUntilChanged()
      .subscribe(this.setTabARootPage.bind(this));
  }

  private setTabARootPage(rootPage) {
    // This is the hack

    // set the root property that we didn't set in the view as [root]="..."
    this.tabRef.root = rootPage;

    /*
    * Modifying private attributes to make it work.
    * This will allow Ionic to run the "tabsInstance.load()" method to load a new root page
    * It also allows us to select the same tab again.
    */
    this.tabRef._loaded = false;
    this.tabsRef._tabs[0].isSelected = false;

    this.tabsRef.select(this.tabRef); // select the tab again
  }

}


问:
Returning zero results on multiple conditions codeigniter
I am currently doing a airline reservation. The fields/radio button/dropdown I have are: 2 radio button(One way, Round trip), 2 dropdown(From ,To:), 1 text field.

After filling up these fields and tried to click the "Search now". It returns no result.

NOTE: My columns on the flight table are: flight_name, flight_destination, flight_depart. I also tried to print/var_dump my variable inside of my search_result both model and controller, the value is correct/right

I also tried to print $table(it getting my flight table), $testing - getting my value, $testing2 and $testing3 is also correct but when I tried to print $query it is NULL/ retuns 0 result.

Model

```<code>public function search($table, $flight_from, $flight_to, $depart)
{
    $this->db->select('*');
    $table = $this->db->from($table);
    $testing = $this->db->where('flight_name',$flight_from)
    $testing2 = $this->db->where('flight_destination',$flight_to)
    $testing3 = $this->db->where('flight_depart',$depart);

    $query = $this->db->get();
    return $query->result();

}
</code>```

Controller

```<code>public function search()
    {
        $this->form_validation->set_error_delimiters('<div class="alert alert-danger" role="alert">', '</div>');
        $this->form_validation->set_rules('flight_from', 'Select depature', 'required|trim');
        $this->form_validation->set_rules('flight_to', 'Select Destination', 'required|trim');
        $this->form_validation->set_rules('depart', 'Date', 'required|trim');

        if ($this->form_validation->run() == FALSE)
        {
            $this->index();

        }
        else
        {
        $search_result = array(
            $flight_from = $_POST['flight_from'],
            $flight_to = $_POST['flight_to'],
            $depart = $_POST['depart']
        );
        $data['search_result'] = $this->CrudModel->search('flight',$flight_from,$flight_to,$depart);

        $this->load->view('result',$data);
        }
    }
</code>```

Question: How is it returning zero result? Even though there's an existing data. Is my query wrong?

答:
```<code>public function search($table, $flight_from, $flight_to, $depart)
{
    $this->db->select('*');
    $this->db->from($table);
    $this->db->where('flight_name',$flight_from)
    $this->db->where('flight_destination',$flight_to)
    $this->db->where('flight_depart',$depart);
    $query = $this->db->get();
    return $query->result();
}
</code>```

Body:
I am currently doing a airline reservation. The fields/radio button/dropdown I have are: 2 radio button(One way, Round trip), 2 dropdown(From ,To:), 1 text field.

After filling up these fields and tried to click the "Search now". It returns no result.

NOTE: My columns on the flight table are: flight_name, flight_destination, flight_depart. I also tried to print/var_dump my variable inside of my search_result both model and controller, the value is correct/right

I also tried to print $table(it getting my flight table), $testing - getting my value, $testing2 and $testing3 is also correct but when I tried to print $query it is NULL/ retuns 0 result.

Model

public function search($table, $flight_from, $flight_to, $depart)
{
    $this->db->select('*');
    $table = $this->db->from($table);
    $testing = $this->db->where('flight_name',$flight_from)
    $testing2 = $this->db->where('flight_destination',$flight_to)
    $testing3 = $this->db->where('flight_depart',$depart);

    $query = $this->db->get();
    return $query->result();

}

Controller

public function search()
    {
        $this->form_validation->set_error_delimiters('
', '
');
        $this->form_validation->set_rules('flight_from', 'Select depature', 'required|trim');
        $this->form_validation->set_rules('flight_to', 'Select Destination', 'required|trim');
        $this->form_validation->set_rules('depart', 'Date', 'required|trim');

        if ($this->form_validation->run() == FALSE)
        {
            $this->index();

        }
        else
        {
        $search_result = array(
            $flight_from = $_POST['flight_from'],
            $flight_to = $_POST['flight_to'],
            $depart = $_POST['depart']
        );
        $data['search_result'] = $this->CrudModel->search('flight',$flight_from,$flight_to,$depart);

        $this->load->view('result',$data);
        }
    }

Question: How is it returning zero result? Even though there's an existing data. Is my query wrong?


问:
How to keep core threads alive and die out excess threads in ThreadPoolExecutor? keepAliveTime doesn't work as expected
I use ThreadPoolExecutor to manage a thread pool. What we want are:

if the pool has less than corePoolSize threads, kick off a new thread for a new task;

if the pool has more than corePoolSize threads and all are busy, kick off a new thread for a new task until maxPoolSize is reached. In that case, reject the task;

keep corePoolSize number of threads alive even if they are idling, excess threads will die if they have been idle for more than keepAliveTime

According the Java6 docs, keepAliveTime should work as above. But in my test code, it doesn't work consistently.

When I set keepAliveTime to 0, it works fine, always keeping core threads alive and terminating excess threads when they finish;

but, as shown below, when I set keepAliveTime to a positive value, it seems that it terminate ALL idle threads, no matter they are core threads or not.

```<code>ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 4, 500, TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>());
assertFalse("Not allow core threads to time out.", executor.allowsCoreThreadTimeOut());
Task task_1 = new Task(1000);
Task task_2 = new Task(1000);
Task task_3 = new Task(1000);
executor.execute(task_1);
executor.execute(task_2);
executor.execute(task_3);
Thread.sleep(1050L);
assertEquals("Completed 3 tasks.", 3, executor.getCompletedTaskCount());
assertEquals("Three threads are in the pool.", 3, executor.getPoolSize());
Thread.sleep(600L);
//////// This assertion will fail: **expected <2> but was <0>**
assertEquals("Two threads are in the pool.", 2, executor.getPoolSize());

////----
private static class Task implements Runnable {
    private long sleepMillis;
    public Task(final long sleepMillis) {
        this.sleepMillis = sleepMillis;
    }
    public void run() {
        try { Thread.sleep(sleepMillis);
        } catch (Exception e) { System.out.println(e); }
    }
}
</code>```

Is there any misunderstanding about keepAliveTime or getPoolSize? If getPoolSize is not the correct API, how can I get to know the number of "alive" threads (idle or busy)?

Thanks in advance.

答: @arosima keepAliveTime only takes effect on excess threads rather than core threads. Core threads will be always kept in the pool. I also wrote another answer to understand, hope it helpful.

Body:
I use ThreadPoolExecutor to manage a thread pool. What we want are:

if the pool has less than corePoolSize threads, kick off a new thread for a new task;

if the pool has more than corePoolSize threads and all are busy, kick off a new thread for a new task until maxPoolSize is reached. In that case, reject the task;

keep corePoolSize number of threads alive even if they are idling, excess threads will die if they have been idle for more than keepAliveTime

According the Java6 docs, keepAliveTime should work as above. But in my test code, it doesn't work consistently.

When I set keepAliveTime to 0, it works fine, always keeping core threads alive and terminating excess threads when they finish;

but, as shown below, when I set keepAliveTime to a positive value, it seems that it terminate ALL idle threads, no matter they are core threads or not.

ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 4, 500, TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>());
assertFalse("Not allow core threads to time out.", executor.allowsCoreThreadTimeOut());
Task task_1 = new Task(1000);
Task task_2 = new Task(1000);
Task task_3 = new Task(1000);
executor.execute(task_1);
executor.execute(task_2);
executor.execute(task_3);
Thread.sleep(1050L);
assertEquals("Completed 3 tasks.", 3, executor.getCompletedTaskCount());
assertEquals("Three threads are in the pool.", 3, executor.getPoolSize());
Thread.sleep(600L);
//////// This assertion will fail: **expected <2> but was <0>**
assertEquals("Two threads are in the pool.", 2, executor.getPoolSize());

////----
private static class Task implements Runnable {
    private long sleepMillis;
    public Task(final long sleepMillis) {
        this.sleepMillis = sleepMillis;
    }
    public void run() {
        try { Thread.sleep(sleepMillis);
        } catch (Exception e) { System.out.println(e); }
    }
}

Is there any misunderstanding about keepAliveTime or getPoolSize? If getPoolSize is not the correct API, how can I get to know the number of "alive" threads (idle or busy)?

Thanks in advance.


问:
Check if a process exists in go way
If I have the PID of a process, is os.FindProcess enough to test for the existing of the process? I mean if it returns err can I assume that it's terminated (or killed)?

Edit:

I've just wrote a wrapper function around kill -s 0 (old-style bash process testing). This works without any problem, but I'm still happy if there is other solutions (done with go libraries) to this problem.:

```<code>func checkPid(pid int) bool {
    out, err := exec.Command("kill", "-s", "0", strconv.Itoa(pid)).CombinedOutput()
    if err != nil {
        log.Println(err)
    }

    if string(out) == "" {
        return true // pid exist
    }
    return false
}
</code>```

答:
On Windows checking the result of os.FindProcess() seems to be enough to check if process is running.

```<code>func isProcessRunning(pid int) bool {
    _, err = os.FindProcess(pid)
    if err != nil {
        return false
    }
    if runtime.GOOS == "windows" {
        return true
    }
    return false // further checking for other systems then Windows is not supported here
}
</code>```

Title: Check if a process exists in go way

Body:
If I have the PID of a process, is os.FindProcess enough to test for the existing of the process? I mean if it returns err can I assume that it's terminated (or killed)?

Edit:

I've just wrote a wrapper function around kill -s 0 (old-style bash process testing). This works without any problem, but I'm still happy if there is other solutions (done with go libraries) to this problem.:

func checkPid(pid int) bool {
    out, err := exec.Command("kill", "-s", "0", strconv.Itoa(pid)).CombinedOutput()
    if err != nil {
        log.Println(err)
    }

    if string(out) == "" {
        return true // pid exist
    }
    return false
}

Body:
On Windows checking the result of os.FindProcess() seems to be enough to check if process is running.

func isProcessRunning(pid int) bool {
    _, err = os.FindProcess(pid)
    if err != nil {
        return false
    }
    if runtime.GOOS == "windows" {
        return true
    }
    return false // further checking for other systems then Windows is not supported here
}


问:
Count number of times the get method in a dict returns the second option
I am trying to build a list from the values of a dictionary, and use the get method to handle the missing values:

```<code>dic = {'foo': 1, 'bar': 2}
list_values = [dic.get(k, 0) for k in ['foo', 'bar', 'baz']]
print(list_values)
>>> [1, 2, 0]
</code>```

The thing is that I want to know how many times the get method returned the second option.

I know I could use a simple loop:

```<code>list_values = []
missing = 0
for k in ['foo', 'bar', 'baz']:
     if k in dic:
         list_values.append(dic[k])
     else:
         missing += 1
         list_values.append(0)
</code>```

But it does not seem really pythonic compared to the list comprehension created beforehand.

Another idea would be to create a function and then use a wrapper to count the number of times the function was called, but the function is called whether or not the key that is called with get exists, as this simple example shows:

```<code>dic = {'a': 1}

# Do something to count the number of times the function was called
def missing_value():
    print('eh')
    return 0

print(dic.get('a', missing_value()))
>>> eh
>>> 1
</code>```

Anyone has a simple and elegant solution or should I resolve to use the loop outside of a comprehension dict ?

答:
The best one i could come up with without ever using get():

```<code>dic = {'foo': 1, 'bar': 2}
search_keys = ['foo', 'bar', 'baz']
missing_keys = [x for x in search_keys if x not in dic.keys()]
print(missing_keys) # prints: ['baz']
print(len(missing_keys)) # prints only the number of missing keys (1)
</code>```

it has the advantage of being readable...

Body:
I am trying to build a list from the values of a dictionary, and use the get method to handle the missing values:

dic = {'foo': 1, 'bar': 2}
list_values = [dic.get(k, 0) for k in ['foo', 'bar', 'baz']]
print(list_values)
>>> [1, 2, 0]

The thing is that I want to know how many times the get method returned the second option.

I know I could use a simple loop:

list_values = []
missing = 0
for k in ['foo', 'bar', 'baz']:
     if k in dic:
         list_values.append(dic[k])
     else:
         missing += 1
         list_values.append(0)

But it does not seem really pythonic compared to the list comprehension created beforehand.

Another idea would be to create a function and then use a wrapper to count the number of times the function was called, but the function is called whether or not the key that is called with get exists, as this simple example shows:

dic = {'a': 1}

# Do something to count the number of times the function was called
def missing_value():
    print('eh')
    return 0

print(dic.get('a', missing_value()))
>>> eh
>>> 1

Anyone has a simple and elegant solution or should I resolve to use the loop outside of a comprehension dict ?

Body:
The best one i could come up with without ever using get():

dic = {'foo': 1, 'bar': 2}
search_keys = ['foo', 'bar', 'baz']
missing_keys = [x for x in search_keys if x not in dic.keys()]
print(missing_keys) # prints: ['baz']
print(len(missing_keys)) # prints only the number of missing keys (1)

it has the advantage of being readable...


问:
Why this .js script stops working and is causing a browser freeze?
I've downloaded this Drupal 8 template and the site is at www.plotujeme.sk. It has an responsive navigation with this .js script:

```<code>function sidebar_menu() {

  var windowsize = jQuerywindow.width(),
      jQuerynav = jQuery("nav"),
      slide = {
          clear: function () {
              jQuerybody.removeClass('toggled');
              jQuery('.overlay').hide();
              jQuery('.easy-sidebar-toggle').prependTo("header");
              //jQuery('#search').prependTo("body");
              jQuery('.navbar.easy-sidebar').removeClass('toggled');
              jQuery('#navbar').removeAttr("style");
          },
          start: function () {
              jQuery('.overlay').show();
              jQuerybody.addClass('toggled');
              jQueryhtml.addClass('easy-sidebar-active');
              jQuerynav.addClass('easy-sidebar');
              jQuery('.easy-sidebar-toggle').prependTo(".easy-sidebar");
              //jQuery('#search').prependTo("#navbar");
              jQuery('#navbar').height(jQuerywindow.height()).css({
                  "padding-top": "60px"
              });
          },
          remove: function () {
              jQuerynav.removeClass('easy-sidebar');
          }
      };

  if (windowsize < 1003) {

      jQuerynav.addClass('easy-sidebar');
      jQuery('.easy-sidebar-toggle').on("click", function (e) {
          e.preventDefault();
          if (jQuerybody.hasClass('toggled')) {
              slide.clear();
          } else {
              slide.start();
          }
      });

      /*
      jQueryhtml.on('swiperight', function () {
          slide.start();
      });

      jQueryhtml.on('swipeleft', function () {
          slide.clear();
      }); */

  } else {
      slide.clear();
      slide.remove();
  }
}
</code>```

and:

```<code>jQuery(document).ready(function () {
    "use strict";

    sidebar_menu();

    jQuery(window).resize(function () {
        sidebar_menu();
    });
});
</code>```

Problem is, that if I open responsive navigation by clicking on hamburger button, it works several times and then it stops working, the page and a browser freezes or is unresponsive for a long time. I also noticed that (even in template preview) sometimes it does not work at all and nothing happens after clicking hamburger icon. When I resize window multiple times sometimes it works sometimes not.

Do you see any error in the script that could possibly cause this problem?

Update: I also tried to use jQuery('.easy-sidebar-toggle').off("click"); just before jQuery('.easy-sidebar-toggle').on("click", function() {...}); but got the same results.

答:
I think the reason might be the following lines in the resize handler:

```<code>jQuerynav.addClass('easy-sidebar');
jQuery('.easy-sidebar-toggle').on("click", ...
</code>```

They are run every time the window is resized by even one pixel, so a few dozen times a second if you drag the window border. Not sure about the first line, whether it adds the class over and over, but the second line certainly adds an event handler multiple times and fills up the stack. That's the reason your browser freezes. It just can't process the hundreds of registered events.

Just a guess, though.

Body:
I've downloaded this Drupal 8 template and the site is at www.plotujeme.sk. It has an responsive navigation with this .js script:

function sidebar_menu() {

  var windowsize = jQuerywindow.width(),
      jQuerynav = jQuery("nav"),
      slide = {
          clear: function () {
              jQuerybody.removeClass('toggled');
              jQuery('.overlay').hide();
              jQuery('.easy-sidebar-toggle').prependTo("header");
              //jQuery('#search').prependTo("body");
              jQuery('.navbar.easy-sidebar').removeClass('toggled');
              jQuery('#navbar').removeAttr("style");
          },
          start: function () {
              jQuery('.overlay').show();
              jQuerybody.addClass('toggled');
              jQueryhtml.addClass('easy-sidebar-active');
              jQuerynav.addClass('easy-sidebar');
              jQuery('.easy-sidebar-toggle').prependTo(".easy-sidebar");
              //jQuery('#search').prependTo("#navbar");
              jQuery('#navbar').height(jQuerywindow.height()).css({
                  "padding-top": "60px"
              });
          },
          remove: function () {
              jQuerynav.removeClass('easy-sidebar');
          }
      };

  if (windowsize < 1003) {

      jQuerynav.addClass('easy-sidebar');
      jQuery('.easy-sidebar-toggle').on("click", function (e) {
          e.preventDefault();
          if (jQuerybody.hasClass('toggled')) {
              slide.clear();
          } else {
              slide.start();
          }
      });

      /*
      jQueryhtml.on('swiperight', function () {
          slide.start();
      });

      jQueryhtml.on('swipeleft', function () {
          slide.clear();
      }); */

  } else {
      slide.clear();
      slide.remove();
  }
}

and:

jQuery(document).ready(function () {
    "use strict";

    sidebar_menu();

    jQuery(window).resize(function () {
        sidebar_menu();
    });
});

Problem is, that if I open responsive navigation by clicking on hamburger button, it works several times and then it stops working, the page and a browser freezes or is unresponsive for a long time. I also noticed that (even in template preview) sometimes it does not work at all and nothing happens after clicking hamburger icon. When I resize window multiple times sometimes it works sometimes not.

Do you see any error in the script that could possibly cause this problem?

Update: I also tried to use jQuery('.easy-sidebar-toggle').off("click"); just before jQuery('.easy-sidebar-toggle').on("click", function() {...}); but got the same results.

Body:
I think the reason might be the following lines in the resize handler:

jQuerynav.addClass('easy-sidebar');
jQuery('.easy-sidebar-toggle').on("click", ...

They are run every time the window is resized by even one pixel, so a few dozen times a second if you drag the window border. Not sure about the first line, whether it adds the class over and over, but the second line certainly adds an event handler multiple times and fills up the stack. That's the reason your browser freezes. It just can't process the hundreds of registered events.

Just a guess, though.


问:
Android Enable Zoom and Pinch Controls in Webview
I'm trying to get zoom controls to display along with pinch to zoom to work in an android webview. Largely referencing this SO.

Right now I have these being set in the onCreate method:

```<code>this._webView.getSettings().setBuiltInZoomControls(true);
this._webView.getSettings().setDisplayZoomControls(true);
this._webView.getSettings().setSupportZoom(true);
</code>```

But nothing appears and the Zoom controls don't appear. I've also tried without setSupportZoom but that didn't seem to help.

As far as I can tell my webview is not wrapped in a scroll view but it is a subclass of Webview:

```<code>class MyWebView extends WebView {
        public MyWebView(Context context) {
            super(context);
        }

        @Override
        public void goBack() {

            super.goBack();
        }

    }
</code>```

So I end up creating it like this:

```<code>if (this._webView == null) {
            this._webView = new MyWebView(this);
            this._webView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            this._webView.getSettings().setJavaScriptEnabled(true);
            this._webView.setWebChromeClient(new WebChromeClient());
            this._webView.setWebViewClient(new WebViewClient());
            this._webView.getSettings().setBuiltInZoomControls(true);
            this._webView.getSettings().setDisplayZoomControls(true);
            this._webView.getSettings().setSupportZoom(true);
            this._webView.loadUrl(this._baseUrl);
        }
</code>```

Any ideas where I'm going wrong?

Thanks!

EDIT:

In onCreate I do this:

```<code> protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(1);
    getWindow().setFlags(1024, 1024);

    RelativeLayout my_layout = generateLayout();

    initUI();

    setContentView(my_layout);
}
</code>```

In generateLayout we create the initial layout and create the holder for the webView:

```<code>private RelativeLayout generateLayout() {
    RelativeLayout my_layout = new RelativeLayout(this);
    my_layout.setId(this.generateViewId());
    my_layout.setLayoutParams(new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.MATCH_PARENT));

    ... more layout stuff

    FrameLayout webViewPlaceholder = new FrameLayout(this);
    this._webViewPlaceholder = webViewPlaceholder;
    webViewPlaceholder.setId(this.generateViewId());
    webViewPlaceholder.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
    RelativeLayout.LayoutParams webViewPlaceholderLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
    webViewPlaceholderLayoutParams.addRule(RelativeLayout.BELOW, rlHeader.getId());
    webViewPlaceholder.setLayoutParams(webViewPlaceholderLayoutParams);

    my_layout.addView(webViewPlaceholder);
 }
</code>```

Then in initUI we create the webView itself:

```<code>@SuppressLint({"SetJavaScriptEnabled"})
protected void initUI() {
    if (this._webView == null) {
        this._webView = new MyWebView(this);
        this._webView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        this._webView.getSettings().setJavaScriptEnabled(true);
        this._webView.setWebChromeClient(new WebChromeClient());
        this._webView.setWebViewClient(new WebViewClient());

        this._webView.getSettings().setSupportZoom(true);
        this._webView.getSettings().setBuiltInZoomControls(true);
        this._webView.getSettings().setDisplayZoomControls(true);

        this._webView.loadUrl(this._baseUrl);

    } else {
        if (this._webView.getProgress() >= 100) {
            this._progressIndicatorView.setVisibility(View.INVISIBLE);
        }
        setNavigationButtonsState();
    }
    this._webViewPlaceholder.addView(this._webView);
}
</code>```

答:
Try below code. </p>

```<code>this._webView.getSettings().setBuiltInZoomControls(true);
this._webView.getSettings().setDisplayZoomControls(true);
</code>```

Body:
I'm trying to get zoom controls to display along with pinch to zoom to work in an android webview. Largely referencing this SO.

Right now I have these being set in the onCreate method:

this._webView.getSettings().setBuiltInZoomControls(true);
this._webView.getSettings().setDisplayZoomControls(true);
this._webView.getSettings().setSupportZoom(true);

But nothing appears and the Zoom controls don't appear. I've also tried without setSupportZoom but that didn't seem to help.

As far as I can tell my webview is not wrapped in a scroll view but it is a subclass of Webview:

class MyWebView extends WebView {
        public MyWebView(Context context) {
            super(context);
        }

        @Override
        public void goBack() {

            super.goBack();
        }

    }

So I end up creating it like this:

if (this._webView == null) {
            this._webView = new MyWebView(this);
            this._webView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            this._webView.getSettings().setJavaScriptEnabled(true);
            this._webView.setWebChromeClient(new WebChromeClient());
            this._webView.setWebViewClient(new WebViewClient());
            this._webView.getSettings().setBuiltInZoomControls(true);
            this._webView.getSettings().setDisplayZoomControls(true);
            this._webView.getSettings().setSupportZoom(true);
            this._webView.loadUrl(this._baseUrl);
        }

Any ideas where I'm going wrong?

Thanks!

EDIT:

In onCreate I do this:

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(1);
    getWindow().setFlags(1024, 1024);

    RelativeLayout my_layout = generateLayout();

    initUI();

    setContentView(my_layout);
}

In generateLayout we create the initial layout and create the holder for the webView:

private RelativeLayout generateLayout() {
    RelativeLayout my_layout = new RelativeLayout(this);
    my_layout.setId(this.generateViewId());
    my_layout.setLayoutParams(new RelativeLayout.LayoutParams(
            RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.MATCH_PARENT));

    ... more layout stuff

    FrameLayout webViewPlaceholder = new FrameLayout(this);
    this._webViewPlaceholder = webViewPlaceholder;
    webViewPlaceholder.setId(this.generateViewId());
    webViewPlaceholder.setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT));
    RelativeLayout.LayoutParams webViewPlaceholderLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
    webViewPlaceholderLayoutParams.addRule(RelativeLayout.BELOW, rlHeader.getId());
    webViewPlaceholder.setLayoutParams(webViewPlaceholderLayoutParams);

    my_layout.addView(webViewPlaceholder);
 }

Then in initUI we create the webView itself:

@SuppressLint({"SetJavaScriptEnabled"})
protected void initUI() {
    if (this._webView == null) {
        this._webView = new MyWebView(this);
        this._webView.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        this._webView.getSettings().setJavaScriptEnabled(true);
        this._webView.setWebChromeClient(new WebChromeClient());
        this._webView.setWebViewClient(new WebViewClient());

        this._webView.getSettings().setSupportZoom(true);
        this._webView.getSettings().setBuiltInZoomControls(true);
        this._webView.getSettings().setDisplayZoomControls(true);

        this._webView.loadUrl(this._baseUrl);

    } else {
        if (this._webView.getProgress() >= 100) {
            this._progressIndicatorView.setVisibility(View.INVISIBLE);
        }
        setNavigationButtonsState();
    }
    this._webViewPlaceholder.addView(this._webView);
}

Body:
Try below code.

this._webView.getSettings().setBuiltInZoomControls(true);
this._webView.getSettings().setDisplayZoomControls(true);


问:
How to enabled/disabled button based on the result from another activity?
i am currently developing an Android game App. But i am having issue regarding passing data in a Private Void Method from the Level1.java to the data in LevelPage.java. Here is the code for Level1.java, it is extremely very long coding of nearly to 500 lines of code. So i will only display the if else condition of the score that will allow to unlock the next Level's button.

Level1.java

In the AlertDialog, if click on Procceed button which is the positive button, it will directly bring to level 2. But of course, even if pressed Proceed button to proceed to Level 2, it must also ensure Level 2 Button is already enabled. But in the neutral button which is Back button in this case, when go back to LevelPage Activity, it should enabled the Level 2 button.

```<code>if (score == 30) {

                AlertDialog.Builder builder = new AlertDialog.Builder(Level1.this);
                builder.setTitle("Level 1 Complete!");
                builder.setMessage("You have won! You have unlock level 2! You can proceed to Level 2 or go back.");
                builder.setPositiveButton("Proceed", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Level1.this, Level2.class);
                        startActivity(intent);
                    }
                });

                builder.setNeutralButton("Back", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Level1.this, LevelPage.class);
                        intent.putExtra("30", score);
                        startActivity(intent);
                    }
                });
                builder.setCancelable(false);
                builder.show();
                runTimer.cancel();
            }
</code>```

Note that gamePlay() is a private void method which just simply means it will continue the game so simply just ignore that.

LevelPage.java

```<code>btnLevel2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickSound.start();
                Intent i = getIntent();
                i.getSerializableExtra("30");
                if (i.equals("30")) {
                    Intent intent = new Intent(LevelPage.this, Level2.class);
                    startActivity(intent);
                } else {
                    btnLevel2.setEnabled(false);
                }

            }
        });
</code>```

Now it can actually disabled the button. But i cannot be able to enabled the button even when it score 30 at the level1 activity. I had no idea what went wrong with able to pass the data from level1 activity to levelpage activity of btn2.setonclicklistener()

答:
```<code>you can do something like this:

builder.setNeutralButton("Back", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Level1.this, LevelPage.class);
                        intent.putExtra("SCORE", score);
                        startActivity(intent);
                    }
                });

//In your level activity where you have btnlvl2
// int or String based on what have you decalred your score varaible
Intent i = getIntent();
String score = i.getStringExtra("SCORE");

if (score.equals(30)){
        btnLevel2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickSound.start();
                    Intent intent = new Intent(LevelPage.this, Level2.class);
                    startActivity(intent);

            }
        });
    }
</code>```

Body:
i am currently developing an Android game App. But i am having issue regarding passing data in a Private Void Method from the Level1.java to the data in LevelPage.java. Here is the code for Level1.java, it is extremely very long coding of nearly to 500 lines of code. So i will only display the if else condition of the score that will allow to unlock the next Level's button.

Level1.java

In the AlertDialog, if click on Procceed button which is the positive button, it will directly bring to level 2. But of course, even if pressed Proceed button to proceed to Level 2, it must also ensure Level 2 Button is already enabled. But in the neutral button which is Back button in this case, when go back to LevelPage Activity, it should enabled the Level 2 button.

if (score == 30) {

                AlertDialog.Builder builder = new AlertDialog.Builder(Level1.this);
                builder.setTitle("Level 1 Complete!");
                builder.setMessage("You have won! You have unlock level 2! You can proceed to Level 2 or go back.");
                builder.setPositiveButton("Proceed", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Level1.this, Level2.class);
                        startActivity(intent);
                    }
                });

                builder.setNeutralButton("Back", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent(Level1.this, LevelPage.class);
                        intent.putExtra("30", score);
                        startActivity(intent);
                    }
                });
                builder.setCancelable(false);
                builder.show();
                runTimer.cancel();
            }

Note that gamePlay() is a private void method which just simply means it will continue the game so simply just ignore that.

LevelPage.java

btnLevel2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clickSound.start();
                Intent i = getIntent();
                i.getSerializableExtra("30");
                if (i.equals("30")) {
                    Intent intent = new Intent(LevelPage.this, Level2.class);
                    startActivity(intent);
                } else {
                    btnLevel2.setEnabled(false);
                }

            }
        });

Now it can actually disabled the button. But i cannot be able to enabled the button even when it score 30 at the level1 activity. I had no idea what went wrong with able to pass the data from level1 activity to levelpage activity of btn2.setonclicklistener()


问:
SSH session through PHP
I am having issues with making an ssh session through PHP. I have looked high and low and cannot figure out how to do this.  I see on one of your posts you state that you are able to make this connection, I would greatly appreciate the help.  I have included a file called 'class.shell2.php' which has the basic functions I need which are to connect to the ssh server and send commands to the terminal.  However when I try to connect to the server it give me an error "Fatal error: Call to undefined function ssh2_connect() in /*/**/**/class.shell2.php on line 62" Please help me.

Thank you

答:
The SSH2 functions (including ssh2_connect()) are not part of the base php distribution.  They're available through PECL.

Check the "Installing/Configuring" page for SSH2 on the PHP documentation site for info about how to install this module.

ContentLicense: CC BY-SA 2.5

Title: SSH session through PHP


问:
HTTP PATCH via POST?
Is there any way to use method PATCH inside either POST or PUT?

I'm using a smart mirror repo on my Raspberry Pi, and the only methods it has for custom commands are GET/POST/PUT. And the only method the GPIO-Server has is PATCH
I've tried put but it just returns a 405 Method Not Allowed.

答: No, it's not possible. HTTP method can be either POST or PATCH, but you can't use one method via another. The only solution I can think of is using a proxy, which would change POST requests to PATCH. For example, you would send a POST request to the proxy server, and the proxy server would send a PATCH request with the same data to the destination server.</p>

Title: HTTP PATCH via POST?


问:
MIPS N-way associative cache
This is a question about memory organization which I have had very difficulty to understand,

Assume we have an N-way set associative cache with the capacity 4096bytes. The
set field size of the address is 7 bits and the tag field 21 bits. If we assume that
the cache is used together with a 32-bit processor, what is then the block size (in
bytes), how many valid bits does the cache contain, and what is the associativity of
the cache?

答:
So, we have the following information about the processor and the cache -

Cache Size = 4096 B

Address bits = 32

Index bits = 7

Tag bits = 21

From the above information you can quickly calculate the number of bits required for the offset field -

Offset bits = Address bits - Tag bits - Index bits

Offset bits = 32 - 21 - 7 = 4

Offset bits = 4

Using the offset bits, you can find the block size, 2**offset bits

Block Size = 16 bytes

Next thing is the associativity of the cache
We know that the index bits = 7.
This means we have 128 blocks. Each block is 16 bytes wide.

Therefore, the number of ways in the cache would be -

Number of ways = Cache Size / (number of blocks * block Size)

Number of ways = 2
Hence the associativity is 2.

Regarding the number of valid bits. Each block requires a valid bit. Hence the number of valid bits would be -

Valid bits = 128*2

Valid bits = 256

Title: MIPS N-way associative cache


问:
tExtractJSONField From tFileInputJSON - Talent Open Studio
I am very new to Talend Open Studio for DI. I am trying to read data from the below JSON File :

```<code>{
"data": [
  {
     "id": "X999_Y999",
     "from": {
        "name": "Tom Brady", "id": "X12"
     },
     "message": "Looking forward to 2010!",
     "actions": [
        {
           "name": "Comment",
           "link": "http://www.facebook.com/X999/posts/Y999"
        },
        {
           "name": "Like",
           "link": "http://www.facebook.com/X999/posts/Y999"
        }
     ],
     "type": "status",
     "created_time": "2010-08-02T21:27:44+0000",
     "updated_time": "2010-08-02T21:27:44+0000"
  },
  {
     "id": "X998_Y998",
     "from": {
        "name": "Peyton Manning", "id": "X18"
     },
     "message": "Where's my contract?",
     "actions": [
        {
           "name": "Comment",
           "link": "http://www.facebook.com/X998/posts/Y998"
        },
        {
           "name": "Like",
           "link": "http://www.facebook.com/X998/posts/Y998"
        }
     ],
     "type": "status",
     "created_time": "2010-08-02T21:27:44+0000",
     "updated_time": "2010-08-02T21:27:44+0000"
   }
 ]
}
</code>```

I want to load three attributes into my table ( id, actions_name and actions_link). So, in the first step (tFileInputJSON) - I tried to do a Loop Json query as below:

Here, am able to extract the rows as I needed. But, then I used a tExtractJSONField to extract individual fields under "actions" for each "id" using XPath expressions as below:

I tried several other ways to extract the fields but could not do this. Also, not able to find any correct post in stack overflow and talent forums very relevant to my question. Could somebody please help?

答:
Arrange the job like ,

tFileInputJSON is like,

tExtractJSONFields is like,

Then you will get output as,

Body:
I am very new to Talend Open Studio for DI. I am trying to read data from the below JSON File :

{
"data": [
  {
     "id": "X999_Y999",
     "from": {
        "name": "Tom Brady", "id": "X12"
     },
     "message": "Looking forward to 2010!",
     "actions": [
        {
           "name": "Comment",
           "link": "http://www.facebook.com/X999/posts/Y999"
        },
        {
           "name": "Like",
           "link": "http://www.facebook.com/X999/posts/Y999"
        }
     ],
     "type": "status",
     "created_time": "2010-08-02T21:27:44+0000",
     "updated_time": "2010-08-02T21:27:44+0000"
  },
  {
     "id": "X998_Y998",
     "from": {
        "name": "Peyton Manning", "id": "X18"
     },
     "message": "Where's my contract?",
     "actions": [
        {
           "name": "Comment",
           "link": "http://www.facebook.com/X998/posts/Y998"
        },
        {
           "name": "Like",
           "link": "http://www.facebook.com/X998/posts/Y998"
        }
     ],
     "type": "status",
     "created_time": "2010-08-02T21:27:44+0000",
     "updated_time": "2010-08-02T21:27:44+0000"
   }
 ]
}

I want to load three attributes into my table ( id, actions_name and actions_link). So, in the first step (tFileInputJSON) - I tried to do a Loop Json query as below:

Here, am able to extract the rows as I needed. But, then I used a tExtractJSONField to extract individual fields under "actions" for each "id" using XPath expressions as below:

I tried several other ways to extract the fields but could not do this. Also, not able to find any correct post in stack overflow and talent forums very relevant to my question. Could somebody please help?


问:
PHP ImageMagick split large image to tiles
I am trying to split a large image to smaller tiles. I tried it using PHP ImageMagick cropImage() and I could do it successfully with the following code.

```<code>for($w = 0; $w < ($large_image_width/$tile_width); $w++){
    for($h = 0; $h < ($large_image_height/$tile_height); $h++){
        $X = $w*$tile_width;
        $Y = $h*$tile_height;

        $image = new Imagick($input_file);
        $image->cropImage($tile_width,$tile_height, $X,$Y);
        $image->writeImage("X" . ($w+1) . "Y" . ($h+1) . ".jpg");
    }
}
</code>```

But it loops through each tile size and load the image again and again.

When I did more research, I found this link, which is a one liner using the command line.

```<code>convert -crop $WIDTHx$HEIGHT@ huge_file.png  tile_%d.png
</code>```

I am wondering if the PHP ImageMagick extension got any function to do the same. Also I am comfortable to switch to Perl or someother library like GD.

答:
libvips has a php binding now and it can do this task very quickly using only a little memory.

For example:

```<code>#!/usr/bin/env php
<?php

require __DIR__ . '/vendor/autoload.php';

use Jcupitt\Vips;

$im = Vips\Image::newFromFile($argv[1]);
$im->dzsave($argv[2], ["overlap" => 0, "tile-size" => 256, "depth" => "one"]);
</code>```

On this laptop with a 10k x 10k jpeg image, I see:

```<code>$ time ./try260.php ~/pics/wtc.jpg x
real    0m2.262s
user    0m3.596s
sys 0m1.256s
</code>```

And it's created 1369 jpeg files in x_files:

```<code>$ ls x_files/0/ | wc
   1369    1369   14319
</code>```

There's a blogpost here about the dzsave operator (the libvips thing that's being used here):

http://libvips.blogspot.co.uk/2013/03/making-deepzoom-zoomify-and-google-maps.html

Body:
I am trying to split a large image to smaller tiles. I tried it using PHP ImageMagick cropImage() and I could do it successfully with the following code.

for($w = 0; $w < ($large_image_width/$tile_width); $w++){
    for($h = 0; $h < ($large_image_height/$tile_height); $h++){
        $X = $w*$tile_width;
        $Y = $h*$tile_height;

        $image = new Imagick($input_file);
        $image->cropImage($tile_width,$tile_height, $X,$Y);
        $image->writeImage("X" . ($w+1) . "Y" . ($h+1) . ".jpg");
    }
}

But it loops through each tile size and load the image again and again.

When I did more research, I found this link, which is a one liner using the command line.

convert -crop $WIDTHx$HEIGHT@ huge_file.png  tile_%d.png

I am wondering if the PHP ImageMagick extension got any function to do the same. Also I am comfortable to switch to Perl or someother library like GD.

Body:
libvips has a php binding now and it can do this task very quickly using only a little memory.

For example:

#!/usr/bin/env php
<?php

require __DIR__ . '/vendor/autoload.php';

use Jcupitt\Vips;

$im = Vips\Image::newFromFile($argv[1]);
$im->dzsave($argv[2], ["overlap" => 0, "tile-size" => 256, "depth" => "one"]);

On this laptop with a 10k x 10k jpeg image, I see:

$ time ./try260.php ~/pics/wtc.jpg x
real    0m2.262s
user    0m3.596s
sys 0m1.256s

And it's created 1369 jpeg files in x_files:

$ ls x_files/0/ | wc
   1369    1369   14319

There's a blogpost here about the dzsave operator (the libvips thing that's being used here):

http://libvips.blogspot.co.uk/2013/03/making-deepzoom-zoomify-and-google-maps.html


问:
Files outside of project directory in angular2 seed project
How do i include file which is outside of project directory angular 2? I have the folder Structure something like this

WebApp(angular2 seed)
Shared(business logic files)
Mobile App

I gave the correct file path in a file in my web app project but i am stuck with this error

http://localhost:5555/Shared/Services/RO/ROStep2Service.js 404 (Not Found)

Can Somebody please help tell me how can i include the file which is outside of my project directory

答:
You can do this by adding your own project specific gulp build tasks, and including these in your build pipeline.
The seed documentation has a section on how to configure these tasks:
https://github.com/mgechev/angular-seed/tree/master/tools#tasks

You can base your task on the existing seed task which copies all prod assets to your build destination folder:

```<code>export = () => {
  let es: any = require('event-stream');
  return gulp.src([
    join(Config.APP_SRC, '**'),
    join(Config.NPM_BASE, '@angular', 'service-worker', 'bundles', 'worker-basic.min.js'),
    '!' + join(Config.APP_SRC, 'tsconfig.json'),
    '!' + join(Config.APP_SRC, '**', '*.ts'),
    '!' + join(Config.APP_SRC, '**', '*.css'),
    '!' + join(Config.APP_SRC, '**', '*.html'),
    '!' + join(Config.APP_SRC, '**', '*.scss'),
    '!' + join(Config.APP_SRC, '**', '*.sass'),
    '!' + join(Config.ASSETS_SRC, '**', '*.js')
  ].concat(Config.TEMP_FILES.map((p) => { return '!' + p; })))
   .pipe(onlyDirs(es))
   .pipe(gulp.dest(Config.APP_DEST));
};
</code>```

From: https://github.com/mgechev/angular-seed/blob/master/tools/tasks/seed/build.assets.prod.ts

Side note:
As an alternative, if you havent travelled too far down the Angular-Seed path, I would recommend you have a look at building your project using the Angular CLI as a much simpler alternative (especially when upgrading versions). https://angular.io/guide/quickstart

As an example of this simplicity, to include new assets with an Angular CLI project, you just modify your angular-cli.json file, to include the path to the file/folder you want included. Simple, and concise.

Body:
You can do this by adding your own project specific gulp build tasks, and including these in your build pipeline.
The seed documentation has a section on how to configure these tasks:
https://github.com/mgechev/angular-seed/tree/master/tools#tasks

You can base your task on the existing seed task which copies all prod assets to your build destination folder:

export = () => {
  let es: any = require('event-stream');
  return gulp.src([
    join(Config.APP_SRC, '**'),
    join(Config.NPM_BASE, '@angular', 'service-worker', 'bundles', 'worker-basic.min.js'),
    '!' + join(Config.APP_SRC, 'tsconfig.json'),
    '!' + join(Config.APP_SRC, '**', '*.ts'),
    '!' + join(Config.APP_SRC, '**', '*.css'),
    '!' + join(Config.APP_SRC, '**', '*.html'),
    '!' + join(Config.APP_SRC, '**', '*.scss'),
    '!' + join(Config.APP_SRC, '**', '*.sass'),
    '!' + join(Config.ASSETS_SRC, '**', '*.js')
  ].concat(Config.TEMP_FILES.map((p) => { return '!' + p; })))
   .pipe(onlyDirs(es))
   .pipe(gulp.dest(Config.APP_DEST));
};

From: https://github.com/mgechev/angular-seed/blob/master/tools/tasks/seed/build.assets.prod.ts

Side note:
As an alternative, if you havent travelled too far down the Angular-Seed path, I would recommend you have a look at building your project using the Angular CLI as a much simpler alternative (especially when upgrading versions). https://angular.io/guide/quickstart

As an example of this simplicity, to include new assets with an Angular CLI project, you just modify your angular-cli.json file, to include the path to the file/folder you want included. Simple, and concise.