问:
GWT code-splitting download progressbar - like gmail
I have to use code-splitting in my project. but anyway there are some codes for initial downloading for first time.

Now I want to show to end-user the progress for code downloading (.cache.html - or other code-splitting) like gmail startup progress.

Would you please help me.

RGDS

答:
Maybe you can try this and please comment if it works or not;

I'll only send html file to you. You could design according to your code.
How this is woking. There is a div element including "loading". When the page lads first simple html loaded and loading text will be displayed. After html file loaded your nocache.js file will start(still your seeing loaidng text). After js file loaded onmoduleload script will start(still text loading seen) and after the all widgets created and your panels etc ready. Try below code and remove "loading" text from screen;

```<code>com.google.gwt.user.client.Element loading = DOM.getElementById("loading");
DOM.removeChild(RootPanel.getBodyElement(), loading);
</code>```

proje.html;

```<code> <!doctype html>
<!-- The DOCTYPE declaration above will set the    -->
<!-- browser's rendering engine into               -->
<!-- "Standards Mode". Replacing this declaration  -->
<!-- with a "Quirks Mode" doctype may lead to some -->
<!-- differences in layout.                        -->

<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">

    <!--                                                               -->
    <!-- Consider inlining CSS to reduce the number of requested files -->
    <!--                                                               -->
    <link type="text/css" rel="stylesheet" href="<proje>.css">
    <link rel="stylesheet" type="text/css" href="resources/css/gxt-all.css" />

    <!--                                           -->
    <!-- Any title is fine                         -->
    <!--                                           -->
    <title><Proje></title>

    <!--                                           -->
    <!-- This script loads your compiled module.   -->
    <!-- If you add any GWT meta tags, they must   -->
    <!-- be added before this line.                -->
    <!--                                           -->
    <script type="text/javascript" language="javascript" src="<proje>/<proje>.nocache.js"></script>
  </head>

  <!--                                           -->
  <!-- The body can have arbitrary html, or      -->
  <!-- you can leave the body empty if you want  -->
  <!-- to create a completely dynamic UI.        -->
  <!--                                           -->
  <body>

    <!-- OPTIONAL: include this if you want history support -->
    <iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe>

    <!-- RECOMMENDED if your web app will not function without JavaScript enabled -->
    <noscript>
      <div style="width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; background-color: white; border: 1px solid red; padding: 4px; font-family: sans-serif">

      </div>
    </noscript>

    <div align="center" id="loading">
        <table style="height:600px;" border="0">
            <tr height="100%">
                <td align="center">
                    <b>Loading...</b>
                </td>
            </tr>
        </table>
    </div>

    <div id="main" style="display:none">
       <table border="0" width="100%" height="100%" align="center" cellspacing="0">
              <tr>
                <td colspan="2" width="100%" id="ustMenuPanel"></td>
              </tr>
              <tr height="100%" valign="top">
                <td id="menuPanel" width="20%"></td>
                <td id="modulPanel" width="80%"></td>
              </tr>
        </table>
    </div>
  </body>
</html>
</code>```

Body:
Maybe you can try this and please comment if it works or not;

I'll only send html file to you. You could design according to your code.
How this is woking. There is a div element including "loading". When the page lads first simple html loaded and loading text will be displayed. After html file loaded your nocache.js file will start(still your seeing loaidng text). After js file loaded onmoduleload script will start(still text loading seen) and after the all widgets created and your panels etc ready. Try below code and remove "loading" text from screen;

com.google.gwt.user.client.Element loading = DOM.getElementById("loading");
DOM.removeChild(RootPanel.getBodyElement(), loading);

proje.html;

 <!doctype html>
<!-- The DOCTYPE declaration above will set the    -->
<!-- browser's rendering engine into               -->
<!-- "Standards Mode". Replacing this declaration  -->
<!-- with a "Quirks Mode" doctype may lead to some -->
<!-- differences in layout.                        -->

<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">

    <!--                                                               -->
    <!-- Consider inlining CSS to reduce the number of requested files -->
    <!--                                                               -->
    <link type="text/css" rel="stylesheet" href="<proje>.css">
    <link rel="stylesheet" type="text/css" href="resources/css/gxt-all.css" />

    <!--                                           -->
    <!-- Any title is fine                         -->
    <!--                                           -->
    <title><Proje></title>

    <!--                                           -->
    <!-- This script loads your compiled module.   -->
    <!-- If you add any GWT meta tags, they must   -->
    <!-- be added before this line.                -->
    <!--                                           -->
    <script type="text/javascript" language="javascript" src="<proje>/<proje>.nocache.js"></script>
  </head>

  <!--                                           -->
  <!-- The body can have arbitrary html, or      -->
  <!-- you can leave the body empty if you want  -->
  <!-- to create a completely dynamic UI.        -->
  <!--                                           -->
  <body>

    <!-- OPTIONAL: include this if you want history support -->
    <iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position:absolute;width:0;height:0;border:0"></iframe>

    <!-- RECOMMENDED if your web app will not function without JavaScript enabled -->
    <noscript>
      <div style="width: 22em; position: absolute; left: 50%; margin-left: -11em; color: red; background-color: white; border: 1px solid red; padding: 4px; font-family: sans-serif">

      </div>
    </noscript>

    <div align="center" id="loading">
        <table style="height:600px;" border="0">
            <tr height="100%">
                <td align="center">
                    <b>Loading...</b>
                </td>
            </tr>
        </table>
    </div>

    <div id="main" style="display:none">
       <table border="0" width="100%" height="100%" align="center" cellspacing="0">
              <tr>
                <td colspan="2" width="100%" id="ustMenuPanel"></td>
              </tr>
              <tr height="100%" valign="top">
                <td id="menuPanel" width="20%"></td>
                <td id="modulPanel" width="80%"></td>
              </tr>
        </table>
    </div>
  </body>
</html>


来源: stackexchange

问:
ssh clone failed in gitolite at a GCP compute engine
After install gitolite in a GCP compute engine and added a new ssh public key in gitolite-admin/keydir/charley_rsa.pub and add a new repo for charley:

conf/gitolite.conf:

```<code>repo test
    RW+     =   charley
</code>```

Then: git clone gitolite-admin in GCP local console is ok.

When we do git clone in remote local pc, it shows 'DENIED by fallthru' error

```<code>git clone ssh://git@serverip/test
Cloning into 'test'...
FATAL: R any test charley_rsa DENIED by fallthru
(or you mis-spelled the reponame)
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

( clone testing (@all) in remote local pc is ok )

答:
finally, it's resolved after updating the public key filename

I used the id: charley in the conf file: gitolite.conf

```<code>repo test
    RW+     =   charley
</code>```

after change the public ssh key filename
from "charley_rsa.pub" to "charley.pub"

```<code>ssh -i ~/.ssh/id_rsa git@serverip info
hello charley, this is git@serverip running gitolite3 v3.6.6-13-g8bde76d on git 1.8.3.1

 R W    gitolite-admin
 R W    test
 R W    testing
</code>```

ContentLicense: CC BY-SA 3.0

Body:
After install gitolite in a GCP compute engine and added a new ssh public key in gitolite-admin/keydir/charley_rsa.pub and add a new repo for charley:

conf/gitolite.conf:

repo test
    RW+     =   charley

Then: git clone gitolite-admin in GCP local console is ok.

When we do git clone in remote local pc, it shows 'DENIED by fallthru' error

git clone ssh://git@serverip/test
Cloning into 'test'...
FATAL: R any test charley_rsa DENIED by fallthru
(or you mis-spelled the reponame)
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

( clone testing (@all) in remote local pc is ok )

Body:
finally, it's resolved after updating the public key filename

I used the id: charley in the conf file: gitolite.conf

repo test
    RW+     =   charley

after change the public ssh key filename
from "charley_rsa.pub" to "charley.pub"

ssh -i ~/.ssh/id_rsa git@serverip info
hello charley, this is git@serverip running gitolite3 v3.6.6-13-g8bde76d on git 1.8.3.1

 R W    gitolite-admin
 R W    test
 R W    testing


问:
How can I disable default splash screen in react-native?
Is there any way to disable the default splash screen, making our app load main page at first?</p>

答:
There is always a loading portion. During this time a splash WILL be shown. You can customize the splash screen though.

On Android - https://stackoverflow.com/a/44380138/1828637

On iOS - iOS Launch screen in React Native


问:
processing animation in loop
so its my first day using processing and i need a bit of help to start with this is my code, im doing the selection sort:

int[] numbers; // Declare array
int currentmin;
int exchange=0;
void setup() {
  frameRate(0.1);
  size(500,500);

numbers = new int[10]; // Create array with 10 cells
   background(105);
  for (int i = 0; i < numbers.length; i++) { // random numbers from 1 to 100
     int r = int(random(1,100));  // create  random numbers

  for (int j=0; j<numbers.length; j++) { //make sure not duplications
      if(numbers[j]==r)
        {r=r+1;}
  }
   numbers[i]=r; //fill array with random numbers
  println(r);
}
 fill(255,0,0);
for (int i = 0; i < numbers.length; i++) { //draw rectangles
  rect(i*40+10,400 ,35, -numbers[i]);

}
 for (int j=0; j < numbers.length; j++){ //set pivot number

     currentmin=numbers[j];
 for (int i=j+1; i < numbers.length; i++){  //find lowest number in array

   if (numbers[i] < currentmin) {
        currentmin = numbers[i];
    }
 }
  for ( int i=j; i<numbers.length;i++){ //swap pivot with lowest number
    if ( numbers[i]==currentmin){
    exchange=numbers[j];
    numbers[j]=numbers[i];
    numbers[i]=exchange;
  //here
    }
   }
 }

}

void draw() {

   background(105);
for (int z = 0; z < numbers.length; z++) {
  rect(z*40+10,400 ,35, -numbers[z]);

    }
}
```

as you can see where i have the comment here im trying to make the thing animated and to see the rectangles change place on each iteration in the first loop, but its not working... any help ? i tried calling draw(); hopelessly but it didnt work... anyway i can get a help ?

答:
This isn't exactly a trivial animation to execute. You should really start with something simpler.

But to answer your question, you wouldn't put your animation inside a for loop. Instead, you need to make it so the draw() function draws a single frame of the animation. Processing automatically calls the draw() function 60 times per second, so by changing what's drawn each time, you create an animation.

Shameless self-promotion: I wrote a tutorial on creating animations in Processing available here.

Title: processing animation in loop

Body:
so its my first day using processing and i need a bit of help to start with this is my code, im doing the selection sort:

int[] numbers; // Declare array
int currentmin;
int exchange=0;
void setup() {
  frameRate(0.1);
  size(500,500);

numbers = new int[10]; // Create array with 10 cells
   background(105);
  for (int i = 0; i < numbers.length; i++) { // random numbers from 1 to 100
     int r = int(random(1,100));  // create  random numbers

  for (int j=0; j<numbers.length; j++) { //make sure not duplications
      if(numbers[j]==r)
        {r=r+1;}
  }
   numbers[i]=r; //fill array with random numbers
  println(r);
}
 fill(255,0,0);
for (int i = 0; i < numbers.length; i++) { //draw rectangles
  rect(i*40+10,400 ,35, -numbers[i]);

}
 for (int j=0; j < numbers.length; j++){ //set pivot number

     currentmin=numbers[j];
 for (int i=j+1; i < numbers.length; i++){  //find lowest number in array

   if (numbers[i] < currentmin) {
        currentmin = numbers[i];
    }
 }
  for ( int i=j; i<numbers.length;i++){ //swap pivot with lowest number
    if ( numbers[i]==currentmin){
    exchange=numbers[j];
    numbers[j]=numbers[i];
    numbers[i]=exchange;
  //here
    }
   }
 }

}

void draw() {

   background(105);
for (int z = 0; z < numbers.length; z++) {
  rect(z*40+10,400 ,35, -numbers[z]);

    }
}

as you can see where i have the comment here im trying to make the thing animated and to see the rectangles change place on each iteration in the first loop, but its not working... any help ? i tried calling draw(); hopelessly but it didnt work... anyway i can get a help ?


问:
Node / Javascript import different modules based on target platform?
I would like to know what methods are available to specify which modules should my app import based on a target platform. I would like to import different implementations  for the same interface in typescript for a browser and for a nodejs.

We have something like

```<code>#ifdef windows
#include "windowsimplementation.h"
#endif
</code>```

In c++

How could i achieve something similar using typescript node and browserify?

答:
In nodejs, you can do it the following way, as per this post: How do I determine the current operating system with Node.js

// in Nodejs
// possible values for process.platform 'darwin', 'freebsd', 'linux', 'sunos' or 'win32'
var moduleString = {
  'win32': 'windows-node-module',
  'darwin': 'darwin-node-module',
  // ... and so on
}

var module = require(moduleString[process.platform]);```
</div>
</div>
</p>

<p>In the browser, you can check the os through the <code>navigator</code> object:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// in Browser
// possible values windows, mac, linux
var moduleString = {
  'win': 'windows-browser-module',
  'mac': 'mac-browser-module',
  'linux': 'linux-browser-module',
}

function getOS(){
  return navigator.appVersion.indexOf("Win") != -1 ? 'win' :
    (navigator.appVersion.indexOf("Mac") != -1) ? 'mac' : 'linux';
}

var module = require(moduleString[getOS()]);</code>```

Body:
I would like to know what methods are available to specify which modules should my app import based on a target platform. I would like to import different implementations  for the same interface in typescript for a browser and for a nodejs.

We have something like

#ifdef windows
#include "windowsimplementation.h"
#endif

In c++

How could i achieve something similar using typescript node and browserify?

Body:
In nodejs, you can do it the following way, as per this post: How do I determine the current operating system with Node.js

// in Nodejs
// possible values for process.platform 'darwin', 'freebsd', 'linux', 'sunos' or 'win32'
var moduleString = {
  'win32': 'windows-node-module',
  'darwin': 'darwin-node-module',
  // ... and so on
}

var module = require(moduleString[process.platform]);

In the browser, you can check the os through the navigator object:

// in Browser
// possible values windows, mac, linux
var moduleString = {
  'win': 'windows-browser-module',
  'mac': 'mac-browser-module',
  'linux': 'linux-browser-module',
}

function getOS(){
  return navigator.appVersion.indexOf("Win") != -1 ? 'win' :
    (navigator.appVersion.indexOf("Mac") != -1) ? 'mac' : 'linux';
}

var module = require(moduleString[getOS()]);


问:
creating loops for my little game
I am making a simple game with Python. And I'm having a hard time making my game loops. Can someone help me complete my little game.</p>

```<code>import random
print ('Welcome to the Lottery')
dollar = 100
print 'Your money: $' + str(dollar)
print 'Enter your bet:'
bet= raw_input('(ex.$100)')

remaining = dollar - int(bet)
if bet <= dollar:
    print 'Your money: $' + str(remaining)
    print 'Bet:$' + bet
elif bet > dollar:
    print 'You don\'t have enough money'
    raw_input('(ex.$100)')
    while bet > dollar:
        print 'You don\'t have enough money'
        raw_input('(ex.$100)')
else:
    print 'You don\'t have any bets.'

raw_input('Enter you number (1-999):')
raw_input('Play? (yes or no)')
for i in range(1):
        (random.randint(1,999))
        print(random.randint(1,999))
</code>```

答:
You can use while as a loop.

For example, if you wanted to keep repeating your program until the user types a specific word (ex. "exit"):

```<code>import random
print ('Welcome to the Lottery')
dollar = 100
bet = ""
while not bet == "exit":
    print 'Your money: $' + str(dollar)
    print 'Enter your bet:'
    bet= raw_input('(ex.$100)')

    remaining = dollar - int(bet)
    if bet <= dollar:
        print 'Your money: $' + str(remaining)
        print 'Bet:$' + bet
    elif bet > 0:
        print 'You don\'t have enough money'
    else:
        print 'You don\'t have any bets.'

    for i in range(1):
            (random.randint(1,999))
            #return(random.randint(1,999))
print("Goodbye!") # Prints 'Goodbye!' after the user types 'exit'.
</code>```

Alternatively, you can use while True for an infinite loop.

Here's some info and examples: http://www.tutorialspoint.com/python/python_while_loop.htm

Title: creating loops for my little game

Body:
I am making a simple game with Python. And I'm having a hard time making my game loops. Can someone help me complete my little game.

import random
print ('Welcome to the Lottery')
dollar = 100
print 'Your money: $' + str(dollar)
print 'Enter your bet:'
bet= raw_input('(ex.$100)')

remaining = dollar - int(bet)
if bet <= dollar:
    print 'Your money: $' + str(remaining)
    print 'Bet:$' + bet
elif bet > dollar:
    print 'You don\'t have enough money'
    raw_input('(ex.$100)')
    while bet > dollar:
        print 'You don\'t have enough money'
        raw_input('(ex.$100)')
else:
    print 'You don\'t have any bets.'

raw_input('Enter you number (1-999):')
raw_input('Play? (yes or no)')
for i in range(1):
        (random.randint(1,999))
        print(random.randint(1,999))

Body:
You can use while as a loop.

For example, if you wanted to keep repeating your program until the user types a specific word (ex. "exit"):

import random
print ('Welcome to the Lottery')
dollar = 100
bet = ""
while not bet == "exit":
    print 'Your money: $' + str(dollar)
    print 'Enter your bet:'
    bet= raw_input('(ex.$100)')

    remaining = dollar - int(bet)
    if bet <= dollar:
        print 'Your money: $' + str(remaining)
        print 'Bet:$' + bet
    elif bet > 0:
        print 'You don\'t have enough money'
    else:
        print 'You don\'t have any bets.'

    for i in range(1):
            (random.randint(1,999))
            #return(random.randint(1,999))
print("Goodbye!") # Prints 'Goodbye!' after the user types 'exit'.

Alternatively, you can use while True for an infinite loop.

Here's some info and examples: http://www.tutorialspoint.com/python/python_while_loop.htm


问:
OpenCV: draw contours of objects in the binary image
Following an example provided at http://docs.opencv.org/trunk/d4/d73/tutorial_py_contours_begin.html
, I use python in Spyder environment to draw contours of detected components in a binary image. My codes are here:

```<code>im = cv2.imread('test.jpg') #raw RGB image
im2 = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) #gray scale image
plt.imshow(im2,cmap = 'gray')
</code>```

The image is shown as follows:

Then,

```<code>thresh, im_bw = cv2.threshold(im2, 127, 255, cv2.THRESH_BINARY) #im_bw: binary image
im3, contours, hierarchy = cv2.findContours(im_bw,cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
cv2.drawContours(im2, contours, -1, (0,255,0), 3)
plt.imshow(im2,cmap='gray')  #without the code, only an array displayed in the console
</code>```

These codes do not give a figure with contours for some reason. But if I change the last two lines of codes as follows:

```<code>cv2.drawContours(im, contours, -1, (0,255,0), 3)
plt.imshow(im,cmap='gray')
</code>```

It yields a figure with contour:

I feel confused about how these codes work? Does cv2.drawCoutours only apply to GRB images? Hope not.
Besides, it is noted that contours[0] gives a 3D array:

```<code>idx = contours[0]
print idx.shape

(392L, 1L, 2L)
</code>```

the idx should store the pixel coordinates of all contour points. But how to interpret what each dimension represents, and get pixel coordinates for each contour point from it? Then I can use these coordinates to draw contours without resorting to cv2.drawContours

答:
Both cv2.findContours and cv2.drawContours are destructive methods, which modify the original input image, and the latter is only applicable to RBG images for plotting, which explain that no visible contours are displayed in a plotted grayscale image.

Besides cv2.drawContours, the contour can be also easily drawn with using the indices of border pixels that are stored in "contours" (in the code above) obtained by cv2.findContours.

Body:
Following an example provided at http://docs.opencv.org/trunk/d4/d73/tutorial_py_contours_begin.html
, I use python in Spyder environment to draw contours of detected components in a binary image. My codes are here:

im = cv2.imread('test.jpg') #raw RGB image
im2 = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) #gray scale image
plt.imshow(im2,cmap = 'gray')

The image is shown as follows:

Then,

thresh, im_bw = cv2.threshold(im2, 127, 255, cv2.THRESH_BINARY) #im_bw: binary image
im3, contours, hierarchy = cv2.findContours(im_bw,cv2.RETR_TREE, cv2.CHAIN_APPROX_NONE)
cv2.drawContours(im2, contours, -1, (0,255,0), 3)
plt.imshow(im2,cmap='gray')  #without the code, only an array displayed in the console

These codes do not give a figure with contours for some reason. But if I change the last two lines of codes as follows:

cv2.drawContours(im, contours, -1, (0,255,0), 3)
plt.imshow(im,cmap='gray')

It yields a figure with contour:

I feel confused about how these codes work? Does cv2.drawCoutours only apply to GRB images? Hope not.
Besides, it is noted that contours[0] gives a 3D array:

idx = contours[0]
print idx.shape

(392L, 1L, 2L)

the idx should store the pixel coordinates of all contour points. But how to interpret what each dimension represents, and get pixel coordinates for each contour point from it? Then I can use these coordinates to draw contours without resorting to cv2.drawContours


问:
OpenCL Kernel for Canny
I'm trying to achieve Canny Edge Detection with OpenCL kernel in very simplified and easy way.

I'm using original SobelFilter kernel to do steps like non-maximum suppression and thresholding.

But I'm lost about reaching the pixels and doing the math calculations on them with:

```<code>__kernel void sobel_filter(__global uchar4* inputImage, __global uchar4* outputImage)
</code>```

Could you give me ideas or show me simple examples to achieve this? It will be highly appreciated.
Regards.

答:
ARM compute library has canny implementation
Canny CL kernel</p>

Title: OpenCL Kernel for Canny

Body:
I'm trying to achieve Canny Edge Detection with OpenCL kernel in very simplified and easy way.

I'm using original SobelFilter kernel to do steps like non-maximum suppression and thresholding.

But I'm lost about reaching the pixels and doing the math calculations on them with:

__kernel void sobel_filter(__global uchar4* inputImage, __global uchar4* outputImage)

Could you give me ideas or show me simple examples to achieve this? It will be highly appreciated.
Regards.


问:
Unity add content dynamicly to NGUI grid
I am using Unity 5.5.2f and NGUI 3.9.4 and I want to take advantage of NGUI's Grid to auto arrange items in perfect display.

The thing is that when I add items in the hierarchy manually things will work fine but when I add items through the script , Grid won't arrange my items.

Here is the code that I use to add items to level board.

```<code>void Start () {

        List<Level> levels = ApplicationModel.Levels;
        GameObject currentWrap = null;
        Debug.LogWarning(levels.Count);
        for (int i = 0; i < levels.Count; i++)
        {
            if(i%4 == 0){

                currentWrap = Instantiate(levelWrap,transform,false);

            }
            if (levels[i].IsLock){

                GameObject go = Instantiate(levelLocked, currentWrap.transform, false);
                go.transform.localPosition = new Vector3(levelXstart + (i % 4) * levelXOffset, 0, 0);

                go.transform.GetComponentInChildren<UILabel>().text = i.ToString();
            }
            else
            {

                GameObject go = Instantiate(levelActive, currentWrap.transform, false);
                go.transform.localPosition = new Vector3(levelXstart + (i % 4) * levelXOffset, 0, 0);
                go.transform.GetComponentInChildren<UILabel>().text = i.ToString();
                for (int j = 0; j < levels[i].StarGet;j++){
                    go.transform.Find("fills").GetChild(j).gameObject.SetActive(true);
                }

            }
        }

    }
</code>```

答:
Ok, I find the trick, after Instantiate the wrap item, I should AddChild() to the grid system.

```<code> if(i%4 == 0)
 {
   currentWrap = Instantiate(levelWrap,transform,false);
   GetComponent<UIGrid>().AddChild(currentWrap.transform);
 }
</code>```

Body:
I am using Unity 5.5.2f and NGUI 3.9.4 and I want to take advantage of NGUI's Grid to auto arrange items in perfect display.

The thing is that when I add items in the hierarchy manually things will work fine but when I add items through the script , Grid won't arrange my items.

Here is the code that I use to add items to level board.

void Start () {

        List<Level> levels = ApplicationModel.Levels;
        GameObject currentWrap = null;
        Debug.LogWarning(levels.Count);
        for (int i = 0; i < levels.Count; i++)
        {
            if(i%4 == 0){

                currentWrap = Instantiate(levelWrap,transform,false);

            }
            if (levels[i].IsLock){

                GameObject go = Instantiate(levelLocked, currentWrap.transform, false);
                go.transform.localPosition = new Vector3(levelXstart + (i % 4) * levelXOffset, 0, 0);

                go.transform.GetComponentInChildren<UILabel>().text = i.ToString();
            }
            else
            {

                GameObject go = Instantiate(levelActive, currentWrap.transform, false);
                go.transform.localPosition = new Vector3(levelXstart + (i % 4) * levelXOffset, 0, 0);
                go.transform.GetComponentInChildren<UILabel>().text = i.ToString();
                for (int j = 0; j < levels[i].StarGet;j++){
                    go.transform.Find("fills").GetChild(j).gameObject.SetActive(true);
                }

            }
        }

    }

Body:
Ok, I find the trick, after Instantiate the wrap item, I should AddChild() to the grid system.

 if(i%4 == 0)
 {
   currentWrap = Instantiate(levelWrap,transform,false);
   GetComponent<UIGrid>().AddChild(currentWrap.transform);
 }


问:
XSLT Muenchian Grouping on different elements based on a common attribute
I am given XML similar to the following that I need to process.

```<code><root>
    <Header/>
    <Customer id="1" date="13/04/2014"/>
    <Account id="1" date="14/04/2014"/>
    <Account id="1" date="01/06/2015"/>
    <Address id="1" date="14/04/2014"/>
    <Customer id="2" date="12/08/2015"/>
    <Account id="2" date="13/08/2015"/>
    <Address id="2" date="13/08/2015"/>
    <Address id="2" date="03/09/2015"/>
    <Address id="2" date="27/01/2017"/>
    <Customer id="3" date="04/10/2015"/>
    <Customer id="3" date="01/02/2017"/>
    <Account id="3" date="05/10/2015"/>
    <Address id="3" date="08/10/2015"/>
    <Address id="3" date="03/09/2016"/>
</root>
</code>```

All of the nodes have more attributes but I stripped them off. Each element has an id and a date.If there are duplicate elements that have the same id then the one with the most recent date is considered valid and the older one should be ignored.

If the older ones can be stripped out at the same time I would like to output it into something like this.

```<code><Customers>
    <Customer id="1">
        <Account/>
        <Address/>
    </Customer>
    <Customer id="2">
        <Account/>
        <Address/>
    </Customer>
    <Customer id="3">
        <Account/>
        <Address/>
    </Customer>
</Customers>
</code>```

If not then it is fine to process the file in two transforms (one to group them by customer id and each customer have multiple Account/Address fields, then in the other transform remove the older entries)

The source XML has close to a million entries so performance is an issue. The transform taking a few minutes is fine, but any more than 15 will not work.

I currently have the following XSLT

```<code><?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

    <xsl:key name="nodes-by-id" match="//root/*" use="@id"/>

    <xsl:template match="root">
        <Customers>
            <xsl:for-each select="*[count(. | key('nodes-by-id', @id)[1]) = 1]">
                <xsl:variable name="current-grouping-key" select="@id"/>
                <xsl:variable name="current-group" select="key('nodes-by-id', $current-grouping-key)"/>
                <Customer>
                    <xsl:attribute name="id">
                        <xsl:value-of select="$current-grouping-key"/>
                    </xsl:attribute>
                    <CustomerElements>
                        <xsl:for-each select="$current-group/Customer">
                            <CustomerElement>
                                <xsl:attribute name="date">
                                    <xsl:value-of select="@date"/>
                                </xsl:attribute>
                            </CustomerElement>
                        </xsl:for-each>
                    </CustomerElements>
                    <xsl:apply-templates select="$current-group"/>
                </Customer>
            </xsl:for-each>
        </Customers>
    </xsl:template>
</xsl:stylesheet>
</code>```

Currently this just tries to group all of the elements by their id, then output all of the Customer elements. I get the following:

```<code><Customers>
    <Customer id="">
        <CustomerElements/>
    </Customer>
    <Customer id="1">
        <CustomerElements/>
    </Customer>
    <Customer id="2">
        <CustomerElements/>
    </Customer>
    <Customer id="3">
        <CustomerElements/>
    </Customer>
</Customers>
</code>```

I get the customer with the blank ID because I don't ignore the header row. My real question is why does the $current-group variable not contain any elements?

Also any tips on how to ignore the header row, and to filter out entries with the older dates.

答:
I got everything sorted. This is a segment of the XSLT I used. More info in the XML comments.</p>

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

    <xsl:key name="nodes-by-id" match="//root/*" use="@id"/>

    <xsl:template match="PR-030">
        <CustomerMeters>
        <!-- Using select="Customer[cou.... instead of select="*[cou... will couse it to ignore the header. However it requres
            the Customer element to be the first element for the icp in the xml. -->
            <xsl:for-each select="Customer[count(. | key('nodes-by-id', @id)[1]) = 1]">
                <xsl:variable name="current-grouping-key" select="@id"/>
                <xsl:variable name="current-group" select="key('nodes-by-id', $current-grouping-key)"/>

                <xsl:variable name="current-group-sorted">
                    <!-- If we sort all nodes by date order, then we can fetch the first Address/Customer/etc... from this group and we will have the latest-->
                    <xsl:for-each select="$current-group">
                        <!-- year -->
                        <xsl:sort select="substring(@date, 7, 4)" order="descending" data-type="number"/>
                        <!-- month -->
                        <xsl:sort select="substring(@date, 4, 2)" order="descending" data-type="number"/>
                        <!-- day -->
                        <xsl:sort select="substring(@date, 1, 2)" order="descending" data-type="number"/>
                        <xsl:copy-of select="current()" />
                    </xsl:for-each>
                </xsl:variable>
                <Customer>
                    <!-- In here I can get what I want from the current-group-sorted varaible-->
                    <!-- Because they are in date order I can just get the first occurance and it will be the most recent-->
                    <someField>
                        <xsl:value-of select="$current-group-sorted/*[self::Account][1]/@someAttribute"/>
                    </someField>
                </Customer>
            </xsl:for-each>
        </CustomerMeters>
    </xsl:template>
</xsl:stylesheet>
</code>```

Body:
I am given XML similar to the following that I need to process.

<root>

    <Customer id="1" date="13/04/2014"/>
    <Account id="1" date="14/04/2014"/>
    <Account id="1" date="01/06/2015"/>
    <Address id="1" date="14/04/2014"/>
    <Customer id="2" date="12/08/2015"/>
    <Account id="2" date="13/08/2015"/>
    <Address id="2" date="13/08/2015"/>
    <Address id="2" date="03/09/2015"/>
    <Address id="2" date="27/01/2017"/>
    <Customer id="3" date="04/10/2015"/>
    <Customer id="3" date="01/02/2017"/>
    <Account id="3" date="05/10/2015"/>
    <Address id="3" date="08/10/2015"/>
    <Address id="3" date="03/09/2016"/>
</root>

All of the nodes have more attributes but I stripped them off. Each element has an id and a date.If there are duplicate elements that have the same id then the one with the most recent date is considered valid and the older one should be ignored.

If the older ones can be stripped out at the same time I would like to output it into something like this.

<Customers>
    <Customer id="1">
        <Account/>
        <Address/>
    </Customer>
    <Customer id="2">
        <Account/>
        <Address/>
    </Customer>
    <Customer id="3">
        <Account/>
        <Address/>
    </Customer>
</Customers>

If not then it is fine to process the file in two transforms (one to group them by customer id and each customer have multiple Account/Address fields, then in the other transform remove the older entries)

The source XML has close to a million entries so performance is an issue. The transform taking a few minutes is fine, but any more than 15 will not work.

I currently have the following XSLT

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

    <xsl:key name="nodes-by-id" match="//root/*" use="@id"/>

    <xsl:template match="root">
        <Customers>
            <xsl:for-each select="*[count(. | key('nodes-by-id', @id)[1]) = 1]">
                <xsl:variable name="current-grouping-key" select="@id"/>
                <xsl:variable name="current-group" select="key('nodes-by-id', $current-grouping-key)"/>
                <Customer>
                    <xsl:attribute name="id">
                        <xsl:value-of select="$current-grouping-key"/>
                    </xsl:attribute>
                    <CustomerElements>
                        <xsl:for-each select="$current-group/Customer">
                            <CustomerElement>
                                <xsl:attribute name="date">
                                    <xsl:value-of select="@date"/>
                                </xsl:attribute>
                            </CustomerElement>
                        </xsl:for-each>
                    </CustomerElements>
                    <xsl:apply-templates select="$current-group"/>
                </Customer>
            </xsl:for-each>
        </Customers>
    </xsl:template>
</xsl:stylesheet>

Currently this just tries to group all of the elements by their id, then output all of the Customer elements. I get the following:

<Customers>
    <Customer id="">
        <CustomerElements/>
    </Customer>
    <Customer id="1">
        <CustomerElements/>
    </Customer>
    <Customer id="2">
        <CustomerElements/>
    </Customer>
    <Customer id="3">
        <CustomerElements/>
    </Customer>
</Customers>

I get the customer with the blank ID because I don't ignore the header row. My real question is why does the $current-group variable not contain any elements?

Also any tips on how to ignore the header row, and to filter out entries with the older dates.

Body:
I got everything sorted. This is a segment of the XSLT I used. More info in the XML comments.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

    <xsl:key name="nodes-by-id" match="//root/*" use="@id"/>

    <xsl:template match="PR-030">
        <CustomerMeters>
        <!-- Using select="Customer[cou.... instead of select="*[cou... will couse it to ignore the header. However it requres
            the Customer element to be the first element for the icp in the xml. -->
            <xsl:for-each select="Customer[count(. | key('nodes-by-id', @id)[1]) = 1]">
                <xsl:variable name="current-grouping-key" select="@id"/>
                <xsl:variable name="current-group" select="key('nodes-by-id', $current-grouping-key)"/>

                <xsl:variable name="current-group-sorted">
                    <!-- If we sort all nodes by date order, then we can fetch the first Address/Customer/etc... from this group and we will have the latest-->
                    <xsl:for-each select="$current-group">
                        <!-- year -->
                        <xsl:sort select="substring(@date, 7, 4)" order="descending" data-type="number"/>
                        <!-- month -->
                        <xsl:sort select="substring(@date, 4, 2)" order="descending" data-type="number"/>
                        <!-- day -->
                        <xsl:sort select="substring(@date, 1, 2)" order="descending" data-type="number"/>
                        <xsl:copy-of select="current()" />
                    </xsl:for-each>
                </xsl:variable>
                <Customer>
                    <!-- In here I can get what I want from the current-group-sorted varaible-->
                    <!-- Because they are in date order I can just get the first occurance and it will be the most recent-->
                    <someField>
                        <xsl:value-of select="$current-group-sorted/*[self::Account][1]/@someAttribute"/>
                    </someField>
                </Customer>
            </xsl:for-each>
        </CustomerMeters>
    </xsl:template>
</xsl:stylesheet>


问:
python web scrape with incremented id
Attempting to scrape a page that list data (table) per student (tr) and its data (td).

Each student listed in a tr has its own unique id tag that increments by 1 for each student.

Example: 1234-1, 1234-2, 1234-3 etc..

I have tried to add to the id by incrementing count variable by 1. Also the output only provides the first td and not all of the td's.

Im new to python and also webscraping and not sure why this is not working. Any help would be much appreciated

```<code>import csv
import requests
from bs4 import BeautifulSoup

url = '' # Has been left blank for a reason
response = requests.get(url)
html = response.content

count = 1

print ('-' * 30)

soup = BeautifulSoup(html, "html.parser")
table = soup.find('tr', attrs={'id': '1234-' + str(count)})

list_of_cells = []

while True:
    for cell in table.findAll('td'):
        text = cell.text.replace('\xa0', '')
        list_of_cells.append(text)
    list_of_cells.append(list_of_cells)

    student_name = list_of_cells[0]
    agent_id = list_of_cells[3].replace('-', '')

    total_hrs = list_of_cells[14]
    total_inc = list_of_cells[15]

    count += 1

    print (student_name, "| ", total_hrs, " ", total_inc)
else:
    print('Done')
</code>```

Example of tr in table..

```<code><tr height="17" id="1234-1" style="height:12.75pt;display:none">
  <td class="xl243045" height="17" style="height:12.75pt;border-top:none">
    <a href="48701">Student Name</a>
  </td>
  <td style="border-top:none;border-left:none">stuff</td>
  <td style="border-top:none;border-left:none">stuff</td>
  <td style="border-top:none;border-left:none">stuff</td>
  <td style="border-top:none;border-left:none">stuff</td>
  <td style="border-top:none;border-left:none">stuff</td>
  <td style="border-top:none;border-left:none">stuff</td>
  <td style="border-top:none;border-left:none">stuff</td>
  <td style="border-top:none;border-left:none">stuff</td>
  <td style="border-top:none;border-left:none">stuff</td>
  <td style="border-top:none;border-left:none">stuff</td>
  <td style="border-top:none;border-left:none">stuff</td>
  <td style="border-top:none;border-left:none">stuff</td>
  <td style="border-top:none;border-left:none">stuff</td>
  <td style="border-top:none;border-left:none">stuff</td>
</tr>
</code>```

答:
The line table = soup.find('tr', attrs={'id': '1234-' + str(count)}) needs to be within the loop where you increase count.

```<code>count = 1

print ('-' * 30)

soup = BeautifulSoup(html, "html.parser")

list_of_cells = []

while True:
    table = soup.find('tr', attrs={'id': '1234-' + str(count)})
    for cell in table.findAll('td'):
        text = cell.text.replace('\xa0', '')
        list_of_cells.append(text)
    list_of_cells.append(list_of_cells)

    student_name = list_of_cells[0]
    agent_id = list_of_cells[3].replace('-', '')

    total_hrs = list_of_cells[14]
    total_inc = list_of_cells[15]

    count += 1

    print (student_name, "| ", total_hrs, " ", total_inc)
else:
    print('Done')
</code>```

ContentLicense: CC BY-SA 4.0

Title: python web scrape with incremented id

Body:
Attempting to scrape a page that list data (table) per student (tr) and its data (td).

Each student listed in a tr has its own unique id tag that increments by 1 for each student.

Example: 1234-1, 1234-2, 1234-3 etc..

I have tried to add to the id by incrementing count variable by 1. Also the output only provides the first td and not all of the td's.

Im new to python and also webscraping and not sure why this is not working. Any help would be much appreciated

import csv
import requests
from bs4 import BeautifulSoup

url = '' # Has been left blank for a reason
response = requests.get(url)
html = response.content

count = 1

print ('-' * 30)

soup = BeautifulSoup(html, "html.parser")
table = soup.find('tr', attrs={'id': '1234-' + str(count)})

list_of_cells = []

while True:
    for cell in table.findAll('td'):
        text = cell.text.replace('\xa0', '')
        list_of_cells.append(text)
    list_of_cells.append(list_of_cells)

    student_name = list_of_cells[0]
    agent_id = list_of_cells[3].replace('-', '')

    total_hrs = list_of_cells[14]
    total_inc = list_of_cells[15]

    count += 1

    print (student_name, "| ", total_hrs, " ", total_inc)
else:
    print('Done')

Example of tr in table..

    Student Name

  stuff
  stuff
  stuff
  stuff
  stuff
  stuff
  stuff
  stuff
  stuff
  stuff
  stuff
  stuff
  stuff
  stuff

Body:
The line table = soup.find('tr', attrs={'id': '1234-' + str(count)}) needs to be within the loop where you increase count.

count = 1

print ('-' * 30)

soup = BeautifulSoup(html, "html.parser")

list_of_cells = []

while True:
    table = soup.find('tr', attrs={'id': '1234-' + str(count)})
    for cell in table.findAll('td'):
        text = cell.text.replace('\xa0', '')
        list_of_cells.append(text)
    list_of_cells.append(list_of_cells)

    student_name = list_of_cells[0]
    agent_id = list_of_cells[3].replace('-', '')

    total_hrs = list_of_cells[14]
    total_inc = list_of_cells[15]

    count += 1

    print (student_name, "| ", total_hrs, " ", total_inc)
else:
    print('Done')


问:
greedy regular expression or logic
Consider the string 'X Y Z' and the substitution

```<code>re.sub('Y|Y Z', '', 'X Y Z')
</code>```

This returns

```<code>'X  Z'
</code>```

When it could have returned 'X ' as well.  Obviously it took the first thing it matched, substituted, and afterwards the pattern for the other alternative no longer matched.

Is there a way to tell the substitution to prefer the longest substitution?

答:
According to Python re documentation - Regular Expression Syntax, | part,

A|B, where A and B can be arbitrary REs, creates a regular expression
  that will match either A or B. An arbitrary number of REs can be
  separated by the '|' in this way. This can be used inside groups (see
  below) as well. As the target string is scanned, REs separated by '|'
  are tried from left to right. When one pattern completely matches,
  that branch is accepted. This means that once A matches, B will not be
  tested further, even if it would produce a longer overall match. In
  other words, the '|' operator is never greedy. To match a literal '|',
  use \|, or enclose it inside a character class, as in [|].

Position the longest pattern before the shorter pattern:

```<code>>>> re.sub('Y Z|Y', '', 'X Y Z')
'X '
</code>```

Title: greedy regular expression or logic

Body:
Consider the string 'X Y Z' and the substitution

re.sub('Y|Y Z', '', 'X Y Z')

This returns

'X  Z'

When it could have returned 'X ' as well.  Obviously it took the first thing it matched, substituted, and afterwards the pattern for the other alternative no longer matched.

Is there a way to tell the substitution to prefer the longest substitution?

Body:
According to Python re documentation - Regular Expression Syntax, | part,

A|B, where A and B can be arbitrary REs, creates a regular expression
  that will match either A or B. An arbitrary number of REs can be
  separated by the '|' in this way. This can be used inside groups (see
  below) as well. As the target string is scanned, REs separated by '|'
  are tried from left to right. When one pattern completely matches,
  that branch is accepted. This means that once A matches, B will not be
  tested further, even if it would produce a longer overall match. In
  other words, the '|' operator is never greedy. To match a literal '|',
  use \|, or enclose it inside a character class, as in [|].

Position the longest pattern before the shorter pattern:

>>> re.sub('Y Z|Y', '', 'X Y Z')
'X '


问:
Output Node.js logs to filesystem
I have a Splunk forwarder managing logs in my production servers, so I really just need to get the output of my node app into a file that Splunk is watching. What is the downside of simply doing the following in production:

```<code>node server.js &> output.log
</code>```

As oppose to handling the log output inside the node process with some sort of logging module...

答:
checkout supervisord which is a logging and babysitting tool which becomes the parent of processes like a node server which can handle redirecting both standard out and standard error to files of your choosing ... besides it will sniff for abends and throw the child process back in when needed

here is a typical config file :  /etc/supervisor/conf.d/supervisord.conf

```<code>[supervisord]
nodaemon=true
logfile=GKE_MASTER_LOGDIR/supervisord_nodejs_GKE_FLAVOR_USER.log
pidfile=GKE_MASTER_LOGDIR/supervisord_nodejs_GKE_FLAVOR_USER.pid
stdout_logfile_maxbytes = 1MB
stderr_logfile_maxbytes = 1MB
logfile_backups = 50
# loglevel = debug

[program:nodejs]
command=/tmp/boot_nodejs.sh %(ENV_MONGO_SERVICE_HOST)s   %(ENV_MONGO_SERVICE_PORT)s
stdout_logfile = GKE_MASTER_LOGDIR/nodejs_GKE_FLAVOR_USER_stdout.log
stderr_logfile = GKE_MASTER_LOGDIR/nodejs_GKE_FLAVOR_USER_stderr.log
stdout_logfile_maxbytes = 1MB
stderr_logfile_maxbytes = 1MB
logfile_backups = 50
autostart = True
autorestart = True
# user = GKE_NON_ROOT_USER
</code>```

in my case this all happens inside a Docker container so here is a snippet of my Dockerfile which launches supervisord which in turn launches nodejs and in so doing redirects stdout / err to logging files which supervisord rotates based on space and/or time ... use of Docker is orthogonal to using supervisord so YMMV

```<code>CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf" ]
</code>```

for completeness below I include the boot_nodejs.sh referenced above

```<code>#!/bin/bash

given_mongo_service_host=$1
given_mongo_service_port=$2

current_dir=$(dirname "${BASH_SOURCE}")

current_timestamp="timestamp "$(date '+%Y%m%d_%H%M%S_%Z')

echo
echo "______________  fresh nodejs server bounce  ______________  $current_timestamp"
echo

# ............... now output same to standard error so its log gets the hat tip

(>&2 echo )
(>&2 echo "______________  fresh nodejs server bounce  ______________  $current_timestamp" )
(>&2 echo )

# ................

export MONGO_URL=mongodb://$given_mongo_service_host:$given_mongo_service_port

type node

node main.js
</code>```

Title: Output Node.js logs to filesystem

Body:
I have a Splunk forwarder managing logs in my production servers, so I really just need to get the output of my node app into a file that Splunk is watching. What is the downside of simply doing the following in production:

node server.js &> output.log

As oppose to handling the log output inside the node process with some sort of logging module...

Body:
checkout supervisord which is a logging and babysitting tool which becomes the parent of processes like a node server which can handle redirecting both standard out and standard error to files of your choosing ... besides it will sniff for abends and throw the child process back in when needed

here is a typical config file :  /etc/supervisor/conf.d/supervisord.conf

[supervisord]
nodaemon=true
logfile=GKE_MASTER_LOGDIR/supervisord_nodejs_GKE_FLAVOR_USER.log
pidfile=GKE_MASTER_LOGDIR/supervisord_nodejs_GKE_FLAVOR_USER.pid
stdout_logfile_maxbytes = 1MB
stderr_logfile_maxbytes = 1MB
logfile_backups = 50
# loglevel = debug

[program:nodejs]
command=/tmp/boot_nodejs.sh %(ENV_MONGO_SERVICE_HOST)s   %(ENV_MONGO_SERVICE_PORT)s
stdout_logfile = GKE_MASTER_LOGDIR/nodejs_GKE_FLAVOR_USER_stdout.log
stderr_logfile = GKE_MASTER_LOGDIR/nodejs_GKE_FLAVOR_USER_stderr.log
stdout_logfile_maxbytes = 1MB
stderr_logfile_maxbytes = 1MB
logfile_backups = 50
autostart = True
autorestart = True
# user = GKE_NON_ROOT_USER

in my case this all happens inside a Docker container so here is a snippet of my Dockerfile which launches supervisord which in turn launches nodejs and in so doing redirects stdout / err to logging files which supervisord rotates based on space and/or time ... use of Docker is orthogonal to using supervisord so YMMV

CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/conf.d/supervisord.conf" ]

for completeness below I include the boot_nodejs.sh referenced above

#!/bin/bash

given_mongo_service_host=$1
given_mongo_service_port=$2

current_dir=$(dirname "${BASH_SOURCE}")

current_timestamp="timestamp "$(date '+%Y%m%d_%H%M%S_%Z')

echo
echo "______________  fresh nodejs server bounce  ______________  $current_timestamp"
echo

# ............... now output same to standard error so its log gets the hat tip

(>&2 echo )
(>&2 echo "______________  fresh nodejs server bounce  ______________  $current_timestamp" )
(>&2 echo )

# ................

export MONGO_URL=mongodb://$given_mongo_service_host:$given_mongo_service_port

type node

node main.js


问:
List.js is not working after creating dynamic element buy Vue.js
After taking every move which i can, i am not be able to fix this issue

I have a list of item which i have to pull from api but when i append the element after getting the responce but list.js is not working it is not searching any thing from the elements.

 in

 this contain word with concatenated word like name+' '+title+' '+number

it is showing error

Uncaught TypeError: Cannot read property 'childNodes' of undefined

here is Html

```<code><input type="text" id="filter_search">
<div id="items">
    <ul class="list list-unstyled">
        <!-- this dynamically created -->
        <li>
            <div class="search-word" hidden></div>
        </li>
        ...
        <li>
            <div class="search-word" hidden></div>
        </li>
        <!-- /this dynamically created -->
    </ul>
</div>
</code>```

Scripts

```<code><script>
    /*========== List Js is Scrtip here ==========*/
    var options = {
        valueNames: ['search-word']
    };

    var items = new List("items", options);

    $(document).on('keypress keyup keydown', "#filter_search", function(){
        items.search($(this).val());
    });

    /*========== Vue Js is Scrtip here ==========*/
    var itemVue = new Vue({
        el: "#items",
        data: {
            items: []
        },
        created() {
        this.postItems()
      },
        methods:{
            postItems : function() {
                thisData = this
                axios.post('http://...', {
                    _token: token,
                  })
                  .then(function (response) {
                    thisData.items = response.data
                  })
                  .catch(function (error) {
                    thisData.error = error
                  })
            }
        }
    });

</script>
</code>```

Please help...

Thanks in advance

答:
You could use vue global nextick</p>

```<code>Vue.nextTick(function () {
    let list = new List(id, options)
  })
</code>```

Body:
After taking every move which i can, i am not be able to fix this issue

I have a list of item which i have to pull from api but when i append the element after getting the responce but list.js is not working it is not searching any thing from the elements.

 in

 this contain word with concatenated word like name+' '+title+' '+number

it is showing error

Uncaught TypeError: Cannot read property 'childNodes' of undefined

here is Html

<input type="text" id="filter_search">

        ...

Scripts

Please help...

Thanks in advance

Body:
You could use vue global nextick

Vue.nextTick(function () {
    let list = new List(id, options)
  })


问:
Is using COUNT(*) or SELECT * a good idea?
I've heard several times that you shouldn't perform COUNT(*) or SELECT * for performance reasons, but wasn't able to dig up some further information about it.

I can imagine that the database is then using all columns for the action, which can be an impressive performance loss, but I'm not sure about that. Does somebody have further information about the topic?

答:
Don't confuse the * in "COUNT(*)" with the * in "SELECT * ". They are completely unrelated but sometimes confused because it's such an odd syntax. There is nothing wrong with using COUNT(*), which just means "count rows".

SELECT * on the other hand means "select all columns". That's generally poor practice because it tightly couples your code to the database schema. That means when you change the table you probably have to change the code even if it should have been unaffected. It increases the impact of any schema change.

SELECT * may also cause a sub-optimal query plan. Either because you didn't really need all columns or because it forces the DBMS to do an extra lookup at runtime to get the list of columns.

ContentLicense: CC BY-SA 2.5


问:
javascript classes call function
I am beginner in programming and I am trying the javascript classes, I want to call the boardCastinit function from the override function onConnMessage, but I am getting this error message, Please help in this issue.

boReferenceError: boardCastInit is not defined

websocket.js

```<code>class websocket extends webSocketModel {

constructor() {
    let server = new Server();
    let mongodb = new mongoDB();
    super(server.server);
}

onConnMessage(message) {

    let clients = this.clients;
    boardCastInit(1);
}

 boardCastInit(data){
       console.log(data)
   }

}

module.exports = websocket;
</code>```

websocketModel.js

```<code>const ws = require('websocket').server;

class webSocketModel {

constructor(httpServer) {
    if(!httpServer) throw 'Null Http Server';
    this.websocket = new ws({ httpServer: httpServer, autoAcceptConnections: false });
    this.websocket.on('request', this.onConnOpen.bind(this));
}

onConnOpen(request) {
    var connection = request.accept('echo-protocol', request.origin);
    console.log('Connection Accepted');

    connection.on('message', this.onConnMessage);
    connection.on('close', this.onConnClose);
}

onConnMessage(message) {
    if (message.type === 'utf8') {
        console.log(message.utf8Data);
    } else if (message.type == 'binary') {
        console.log(message.binaryData.length + 'bytes');
    }
}

onConnClose(reasonCode, description) {
    console.log('Connection Closed');
}
}

module.exports = webSocketModel;
</code>```

答:
just change boardCastInit(1) to this.boardCastInit(1)

```<code>onConnMessage(message) {

    let clients = this.clients;
    this.boardCastInit(1);
}
</code>```

Title: javascript classes call function

Body:
I am beginner in programming and I am trying the javascript classes, I want to call the boardCastinit function from the override function onConnMessage, but I am getting this error message, Please help in this issue.

boReferenceError: boardCastInit is not defined

websocket.js

class websocket extends webSocketModel {

constructor() {
    let server = new Server();
    let mongodb = new mongoDB();
    super(server.server);
}

onConnMessage(message) {

    let clients = this.clients;
    boardCastInit(1);
}

 boardCastInit(data){
       console.log(data)
   }

}

module.exports = websocket;

websocketModel.js

const ws = require('websocket').server;

class webSocketModel {

constructor(httpServer) {
    if(!httpServer) throw 'Null Http Server';
    this.websocket = new ws({ httpServer: httpServer, autoAcceptConnections: false });
    this.websocket.on('request', this.onConnOpen.bind(this));
}

onConnOpen(request) {
    var connection = request.accept('echo-protocol', request.origin);
    console.log('Connection Accepted');

    connection.on('message', this.onConnMessage);
    connection.on('close', this.onConnClose);
}

onConnMessage(message) {
    if (message.type === 'utf8') {
        console.log(message.utf8Data);
    } else if (message.type == 'binary') {
        console.log(message.binaryData.length + 'bytes');
    }
}

onConnClose(reasonCode, description) {
    console.log('Connection Closed');
}
}

module.exports = webSocketModel;

Body:
just change boardCastInit(1) to this.boardCastInit(1)

onConnMessage(message) {

    let clients = this.clients;
    this.boardCastInit(1);
}


问:
How do I change an attribute or class using only Javascript?
I would like to change the styling attribute values of all elements that have the class "post-feature" and contain an attribute value of "http"

So the div element will look like the following:

So far the http check works. But I am not able to set the attribute value.

I have the following code

```<code>var features = document.getElementsByClassName(".post-feature")
[0].getAttribute("style");

if (features.includes("http")) {
features.setAttribute("background-color", "orange");

} else {

  alert('no change');

}
</code>```

答:
First, you can use querySelctorAll() with a CSS query that selects the elements with the class you desire and, in most cases, you should use this instead of getElementsByClassName() as that returns a "live node list" that causes the DOM to be re-scanned every time you access it.

Next, setAttribute() is for setting HTML element attributes. You are asking to change the value of a CSS property. While that could be accomplished with setAttribute('style', value), it is very "old-school" and not the best approach, nor is getAttribute('style') the best way to read a CSS property value (it won't work if the CSS was set from a style sheet).

Also, your code is trying to access: backgroundimage, but the property is accessed as background-image when working in CSS and backgroundImage when accessing it via JavaScript.

To access the inline styles applied to an HTML element, just access the style property of that element, followed by the name of the CSS property you are interested in. For example:

```<code>var bColor = element.style.backgroundColor;
</code>```

If the style has been applied to the element from an internal style sheet or an external style sheet, the above approach won't work for you and you'll need to get it another way, via window.getComputedStyle():

```<code>var bColor = window.getComputedStyle(element, null).backgroundColor;
</code>```

But, note that getComputedStyle() doesn't always return the same value that you set - - it's the value after the browser has computed all factors. In this case, even paths that you wrote as relative references (without the "http") will be returned as absolute paths (with the http).

So, here is a modern approach that correctly checks only the background-image CSS property for the presence of http.

NOTE: This solution tests for http specifically in the background-image property. Unlike most of the other answers given, this code will correctly ignore http in other CSS properties besides background-image. Examine the CSS of the last div to see this in action.

// querySelectorAll() is more efficient than getElementsByClassName()
var features = document.querySelectorAll(".post-feature");

// Loop over the list
for(var i = 0; i < features.length; i++){

  // Get access to the background-image property (called backgroundImage from JavaScript) value,
  // convert that value to lower case and check to see if "http" is in that value
  if(features[i].style.backgroundImage.toLowerCase().indexOf("http") > -1){

    // Set the CSS background-color property (called "backgroundColor" in JavaScript) to orange:
    features[i].style.backgroundColor = "orange";

    // Just for testing:
    features[i].textContent = features[i].style.backgroundImage;

  } else {

    alert("No change");

  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.post-feature { width:100%; height:50px; border:1px solid black; background-color:gray; color:yellow; }</code>```

I have "http" in one of my CSS properties, but not "background-image", so I shouldn't be orange.
```

Body:
I would like to change the styling attribute values of all elements that have the class "post-feature" and contain an attribute value of "http"

So the div element will look like the following:

So far the http check works. But I am not able to set the attribute value.

I have the following code

var features = document.getElementsByClassName(".post-feature")
[0].getAttribute("style");

if (features.includes("http")) {
features.setAttribute("background-color", "orange");

} else {

  alert('no change');

}

Body:
First, you can use querySelctorAll() with a CSS query that selects the elements with the class you desire and, in most cases, you should use this instead of getElementsByClassName() as that returns a "live node list" that causes the DOM to be re-scanned every time you access it.

Next, setAttribute() is for setting HTML element attributes. You are asking to change the value of a CSS property. While that could be accomplished with setAttribute('style', value), it is very "old-school" and not the best approach, nor is getAttribute('style') the best way to read a CSS property value (it won't work if the CSS was set from a style sheet).

Also, your code is trying to access: backgroundimage, but the property is accessed as background-image when working in CSS and backgroundImage when accessing it via JavaScript.

To access the inline styles applied to an HTML element, just access the style property of that element, followed by the name of the CSS property you are interested in. For example:

var bColor = element.style.backgroundColor;

If the style has been applied to the element from an internal style sheet or an external style sheet, the above approach won't work for you and you'll need to get it another way, via window.getComputedStyle():

var bColor = window.getComputedStyle(element, null).backgroundColor;

But, note that getComputedStyle() doesn't always return the same value that you set - - it's the value after the browser has computed all factors. In this case, even paths that you wrote as relative references (without the "http") will be returned as absolute paths (with the http).

So, here is a modern approach that correctly checks only the background-image CSS property for the presence of http.

NOTE: This solution tests for http specifically in the background-image property. Unlike most of the other answers given, this code will correctly ignore http in other CSS properties besides background-image. Examine the CSS of the last div to see this in action.

// querySelectorAll() is more efficient than getElementsByClassName()
var features = document.querySelectorAll(".post-feature");

// Loop over the list
for(var i = 0; i < features.length; i++){

  // Get access to the background-image property (called backgroundImage from JavaScript) value,
  // convert that value to lower case and check to see if "http" is in that value
  if(features[i].style.backgroundImage.toLowerCase().indexOf("http") > -1){

    // Set the CSS background-color property (called "backgroundColor" in JavaScript) to orange:
    features[i].style.backgroundColor = "orange";

    // Just for testing:
    features[i].textContent = features[i].style.backgroundImage;

  } else {

    alert("No change");

  }
}

.post-feature { width:100%; height:50px; border:1px solid black; background-color:gray; color:yellow; }

<!-- The correct CSS property is "background-image", not "backgroundimage" -->
<div class="post-feature" style="background-image:url(http://local.test.com/test_image.jpg);"></div>
<div class="post-feature" style="background-image:url(test_image.jpg);"></div>
<div class="post-feature" style="background-image:url(http://local.test.com/test_image.jpg);"></div>
<div class="post-feature"
     style="border-image: url('http:///images/border.png') 30 30 repeat;background-image:url(test_image.jpg);">I have "http" in one of my CSS properties, but not "background-image", so I shouldn't be orange.</div>


问:
How do I use 2 gesture recognizers to receive events simultaneously?
I'm using swipe gestures to navigate between tabs using a fake UITabBarController that hosts 4 UIViewController subclasses inside of a UIScrollView, with UIPanGestureRecognizers on each of them to detect swipes and switch tabs accordingly. The resulting effect is core navigation like what you see on Snapchat. However, one of these screens houses a map view (Mapbox map), which has its own gesture recognizers built-in.

I'd like for the user to be able to swipe on the map itself to navigate to another tab by detecting a swipe from the very right edge of the screen. I've tried adding a UIPanGestureRecognizer to an invisible UIView in this area on the right side, but this provides for a jerky, unanimated tab switch, and it intercepts touch events from the map below.

How can I allow for both gesture recognizers to receive events simultaneously, or filter out some events based upon only the start position of the swipe and its distance and direction?

Code for swiping view controller:

```<code>class KUSwipeViewController: EZSwipeController {

    fileprivate var fakeTabBar: UIView!

    fileprivate var tabBarHeight: CGFloat = 50

    override func viewDidLoad() {
        initUI()
    }

    override func setupView() {
        super.setupView()
        datasource = self
        navigationBarShouldNotExist = true
    }

    func initUI() {
        fakeTabBar = UIView(frame: CGRect(x: 0, y: Screen.height - tabBarHeight, width: Screen.width, height: tabBarHeight))
        fakeTabBar.backgroundColor = .black

        let tab0 = UIButton(frame: CGRect(x: Screen.width * 0.08, y: 9, width: 32, height: 32))
        tab0.setBackgroundImage(#imageLiteral(resourceName: "tab-events"), for: .normal)
        tab0.addTarget(self, action: #selector(tapped0), for: .touchUpInside)
        fakeTabBar.addSubview(tab0)

        let tab1 = UIButton(frame: CGRect(x: Screen.width * 0.32, y: 9, width: 32, height: 32))
        tab1.setBackgroundImage(#imageLiteral(resourceName: "tab-feat"), for: .normal)
        tab1.addTarget(self, action: #selector(tapped1), for: .touchUpInside)
        fakeTabBar.addSubview(tab1)

        let tab2 = UIButton(frame: CGRect(x: Screen.width * 0.58, y: 9, width: 32, height: 32))
        tab2.setBackgroundImage(#imageLiteral(resourceName: "tab-chat"), for: .normal)
        tab2.addTarget(self, action: #selector(tapped2), for: .touchUpInside)
        fakeTabBar.addSubview(tab2)

        let tab3 = UIButton(frame: CGRect(x: Screen.width * 0.82, y: 9, width: 32, height: 32))
        tab3.setBackgroundImage(#imageLiteral(resourceName: "tab-profile"), for: .normal)
        tab3.addTarget(self, action: #selector(tapped3), for: .touchUpInside)
        fakeTabBar.addSubview(tab3)

        view.addSubview(fakeTabBar)
    }

    func tapped0() {
        self.moveToPage(0, animated: true)
    }

    func tapped1() {
        self.moveToPage(1, animated: true)
    }

    func tapped2() {
        self.moveToPage(2, animated: true)
    }

    func tapped3() {
        self.moveToPage(3, animated: true)
    }
}

extension KUSwipeViewController: EZSwipeControllerDataSource {
    func viewControllerData() -> [UIViewController] {

        let nav0 = UINavigationController()
        let nav3 = UINavigationController()

        let mapVC = EventMapViewController()
        let featuredVC = FeaturedEventsViewController()
        let chatVC = MessagesViewController()
        let profileVC = ProfileViewController()

        nav0.viewControllers = [mapVC]
        nav3.viewControllers = [profileVC]

        return [nav0, featuredVC, chatVC, nav3]
    }

    func titlesForPages() -> [String] {
        return ["", "", "", ""]
    }

    func indexOfStartingPage() -> Int {
        return 0
    }

    func changedToPageIndex(_ index: Int) {
        Haptic.selection.generate()
    }
}
</code>```

Code for map view controller:

```<code>class EventMapViewController: CommonViewController {

    fileprivate var mapView: MGLMapView!
    fileprivate var statusBarView: UIView!
    fileprivate var searchBar: FloatingSearchBar!
    fileprivate var searchButton: UIButton!
    fileprivate var filterButton: UIButton!
    fileprivate var peekView: UIView!
    fileprivate var architectView: UIView!
    fileprivate var panArchitectView: UIView!
    fileprivate var peekArchitectView: UIView!
    fileprivate var peekLabel: UILabel!
    fileprivate var panView: UIPanGestureRecognizer!

    fileprivate let peekViewHeight: CGFloat = 140

    fileprivate var selectedEvent: Event?

    fileprivate var cardShowing: Bool = false
    fileprivate var peekShowing: Bool = false

    /*
    override func statusBarStyle() -> UIStatusBarStyle {
        return cardShowing ? .lightContent : .default
    }
    */

    override func navigationBarHidden() -> Bool {
        return true
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "eventSegue" {
            let dvc = segue.destination as! EventViewController
            dvc.event = selectedEvent!
        }
    }

    func initUI() {
        mapView = MGLMapView(frame: view.bounds)
        mapView.styleURL = (UIColor.theme == .light) ? URL(string: mbThemeLight)! : URL(string: mbThemeDark)!
        mapView.showsUserLocation = true
        mapView.userTrackingMode = .none
        mapView.delegate = self
        mapView.setCenter(CLLocationCoordinate2D(latitude: 34, longitude: -118), zoomLevel: 5, animated: false)
        view.addSubview(mapView)
        mapView.snp.makeConstraints { (make) in
            make.edges.equalTo(view)
        }

        //architect view (for intercepting touch)
        architectView = UIView(frame: self.view.bounds)
        let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(EventMapViewController.handleTap(gestureRecognizer:)))
        gestureRecognizer.delegate = self
        architectView.addGestureRecognizer(gestureRecognizer)
        architectView.isHidden = true
        view.addSubview(architectView)

        statusBarView = UIView()
        statusBarView.backgroundColor = UIColor.clear
        view.addSubview(statusBarView)
        statusBarView.snp.makeConstraints { (make) in
            make.left.right.top.equalTo(0)
            make.height.equalTo(20)
        }

        searchButton = UIButton()
        searchButton.backgroundColor = UIColor.kuLightBackground
        searchButton.tintColor = (UIColor.theme == .light) ? UIColor.kuPrimary : UIColor.kuDeselected
        searchButton.setImage(#imageLiteral(resourceName: "icon_search_white").withRenderingMode(.alwaysTemplate), for: .normal)
        searchButton.layer.cornerRadius = 25
        searchButton.layer.borderColor = UIColor.kuExtraLightBackground.cgColor
        searchButton.layer.borderWidth = 1
        searchButton.addTarget(self, action: #selector(searchButtonTapped(_:)), for: .touchUpInside)
        view.addSubview(searchButton)
        searchButton.snp.makeConstraints { (make) in
            make.width.height.equalTo(50)
            make.left.equalTo(24)
            make.top.equalTo(34)
        }

        filterButton = UIButton()
        filterButton.backgroundColor = UIColor.kuLightBackground
        filterButton.tintColor = (UIColor.theme == .light) ? UIColor.kuPrimary : UIColor.kuDeselected
        filterButton.setImage(#imageLiteral(resourceName: "icon_filter_white").withRenderingMode(.alwaysTemplate), for: .normal)
        filterButton.layer.cornerRadius = 20
        filterButton.layer.borderColor = UIColor.kuExtraLightBackground.cgColor
        filterButton.layer.borderWidth = 1
        filterButton.addTarget(self, action: #selector(filterButtonTapped(_:)), for: .touchUpInside)
        view.addSubview(filterButton)
        filterButton.snp.makeConstraints { (make) in
            make.width.height.equalTo(40)
            make.left.equalTo(80)
            make.top.equalTo(40)
        }

        //peek view
        peekView = UIView(frame: CGRect(x: 0, y: UIScreen.main.bounds.height, width: UIScreen.main.bounds.width, height: peekViewHeight))
        peekView.backgroundColor = UIColor(white: 1, alpha: 0.5)
        peekView.layer.cornerRadius = 10
        view.addSubview(peekView)

        //peek label
        peekLabel = UILabel(frame: CGRect(x: 0, y: 12, width: UIScreen.main.bounds.width, height: 68))
        peekLabel.font = UIFont.kuBoldFont(ofSize: 38)
        peekLabel.textColor = .black
        peekLabel.textAlignment = .center
        peekView.addSubview(peekLabel)

        //peek architect
        peekArchitectView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: peekViewHeight))
        let peekGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(EventMapViewController.peekSelected(gestureRecognizer:)))
        peekGestureRecognizer.delegate = self
        peekArchitectView.addGestureRecognizer(peekGestureRecognizer)
        peekView.addSubview(peekArchitectView)

        loadEventAnnotations()
    }

    func enterPeekView() {
        guard !peekShowing else { return }

        architectView.isHidden = false
        peekLabel.text = "\(selectedEvent!.title!) >"

        peekView.cheetah
            .move(0, peekViewHeight * -1)
            .duration(0.18)
            .easeOutExpo
            .run()

        peekShowing = true
    }

    func exitPeekView() {
        guard peekShowing else { return }

        architectView.isHidden = true
        peekView.cheetah
            .move(0, peekViewHeight)
            .duration(0.18)
            .easeInExpo
            .run()

        peekShowing = false
    }

    func loadEventAnnotations() {
        RealmManager.shared.defaultRealm.objects(Event.self).forEach { (event) in

            let annotation = EventAnnotation()
            annotation.event = event
            mapView.addAnnotation(annotation)
        }
    }

    func searchButtonTapped(_ sender: UIButton) {
        let eventSearchCardViewController = EventSearchCardViewController()
        eventSearchCardViewController.delegate = self
        UIApplication.rootViewController()?.presentCardViewController(eventSearchCardViewController)
    }

    func filterButtonTapped(_ sender: UIButton) {
        let eventFilterCardViewController = EventFilterCardViewController()
        eventFilterCardViewController.delegate = self
        UIApplication.rootViewController()?.presentCardViewController(eventFilterCardViewController)
    }
}

extension EventMapViewController: CardViewControllerDelegate {

    func cardViewControllerWillAppear(cardViewController: CardViewController) {
        cardShowing = true
        setNeedsStatusBarAppearanceUpdate()
    }

    func cardViewControllerWillDisappear(cardViewController: CardViewController) {
        cardShowing = false
        setNeedsStatusBarAppearanceUpdate()
    }
}

extension EventMapViewController: MGLMapViewDelegate {

    func mapView(_ mapView: MGLMapView, didSelect annotation: MGLAnnotation) {

        guard let eventAnnotation = annotation as? EventAnnotation else {
            return
        }

        selectedEvent = eventAnnotation.event

        enterPeekView()
    }

    func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
        return false
    }

    func mapView(_ mapView: MGLMapView, imageFor annotation: MGLAnnotation) -> MGLAnnotationImage? {
        var annotationImage = mapView.dequeueReusableAnnotationImage(withIdentifier: UIColor.kuMarkerName)

        if annotationImage == nil {
            var image = UIImage(named: UIColor.kuMarkerName)!
            image = image.withAlignmentRectInsets(UIEdgeInsets(top: 0, left: 0, bottom: image.size.height/2, right: 0))
            annotationImage = MGLAnnotationImage(image: image, reuseIdentifier: UIColor.kuMarkerName)
        }

        return annotationImage
    }
}

extension EventMapViewController: UIGestureRecognizerDelegate {

    func handleTap(gestureRecognizer: UIGestureRecognizer) {
        //close peek and keyboard on tap
        view.endEditing(true)

        if peekShowing {
            exitPeekView()
        }
    }

    func peekSelected(gestureRecognizer: UIGestureRecognizer) {
//        performSegue(withIdentifier: "eventSegue", sender: nil)

        let eventController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "EventViewController") as! EventViewController
        self.navigationController?.pushViewController(eventController, animated: true)
    }
}
</code>```

答:
To use multiple gestures make your class a GestureRecognizer delegate UIGestureRecoginizerDelegate then use this function:

```<code>func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        if (gestureRecognizer is UIPanGestureRecognizer || gestureRecognizer is UITapGestureRecognizer) {
            return true
        } else {
            return false
        }
    }
</code>```

Body:
I'm using swipe gestures to navigate between tabs using a fake UITabBarController that hosts 4 UIViewController subclasses inside of a UIScrollView, with UIPanGestureRecognizers on each of them to detect swipes and switch tabs accordingly. The resulting effect is core navigation like what you see on Snapchat. However, one of these screens houses a map view (Mapbox map), which has its own gesture recognizers built-in.

I'd like for the user to be able to swipe on the map itself to navigate to another tab by detecting a swipe from the very right edge of the screen. I've tried adding a UIPanGestureRecognizer to an invisible UIView in this area on the right side, but this provides for a jerky, unanimated tab switch, and it intercepts touch events from the map below.

How can I allow for both gesture recognizers to receive events simultaneously, or filter out some events based upon only the start position of the swipe and its distance and direction?

Code for swiping view controller:

class KUSwipeViewController: EZSwipeController {

    fileprivate var fakeTabBar: UIView!

    fileprivate var tabBarHeight: CGFloat = 50

    override func viewDidLoad() {
        initUI()
    }

    override func setupView() {
        super.setupView()
        datasource = self
        navigationBarShouldNotExist = true
    }

    func initUI() {
        fakeTabBar = UIView(frame: CGRect(x: 0, y: Screen.height - tabBarHeight, width: Screen.width, height: tabBarHeight))
        fakeTabBar.backgroundColor = .black

        let tab0 = UIButton(frame: CGRect(x: Screen.width * 0.08, y: 9, width: 32, height: 32))
        tab0.setBackgroundImage(#imageLiteral(resourceName: "tab-events"), for: .normal)
        tab0.addTarget(self, action: #selector(tapped0), for: .touchUpInside)
        fakeTabBar.addSubview(tab0)

        let tab1 = UIButton(frame: CGRect(x: Screen.width * 0.32, y: 9, width: 32, height: 32))
        tab1.setBackgroundImage(#imageLiteral(resourceName: "tab-feat"), for: .normal)
        tab1.addTarget(self, action: #selector(tapped1), for: .touchUpInside)
        fakeTabBar.addSubview(tab1)

        let tab2 = UIButton(frame: CGRect(x: Screen.width * 0.58, y: 9, width: 32, height: 32))
        tab2.setBackgroundImage(#imageLiteral(resourceName: "tab-chat"), for: .normal)
        tab2.addTarget(self, action: #selector(tapped2), for: .touchUpInside)
        fakeTabBar.addSubview(tab2)

        let tab3 = UIButton(frame: CGRect(x: Screen.width * 0.82, y: 9, width: 32, height: 32))
        tab3.setBackgroundImage(#imageLiteral(resourceName: "tab-profile"), for: .normal)
        tab3.addTarget(self, action: #selector(tapped3), for: .touchUpInside)
        fakeTabBar.addSubview(tab3)

        view.addSubview(fakeTabBar)
    }

    func tapped0() {
        self.moveToPage(0, animated: true)
    }

    func tapped1() {
        self.moveToPage(1, animated: true)
    }

    func tapped2() {
        self.moveToPage(2, animated: true)
    }

    func tapped3() {
        self.moveToPage(3, animated: true)
    }
}

extension KUSwipeViewController: EZSwipeControllerDataSource {
    func viewControllerData() -> [UIViewController] {

        let nav0 = UINavigationController()
        let nav3 = UINavigationController()

        let mapVC = EventMapViewController()
        let featuredVC = FeaturedEventsViewController()
        let chatVC = MessagesViewController()
        let profileVC = ProfileViewController()

        nav0.viewControllers = [mapVC]
        nav3.viewControllers = [profileVC]

        return [nav0, featuredVC, chatVC, nav3]
    }

    func titlesForPages() -> [String] {
        return ["", "", "", ""]
    }

    func indexOfStartingPage() -> Int {
        return 0
    }

    func changedToPageIndex(_ index: Int) {
        Haptic.selection.generate()
    }
}

Code for map view controller:

class EventMapViewController: CommonViewController {

    fileprivate var mapView: MGLMapView!
    fileprivate var statusBarView: UIView!
    fileprivate var searchBar: FloatingSearchBar!
    fileprivate var searchButton: UIButton!
    fileprivate var filterButton: UIButton!
    fileprivate var peekView: UIView!
    fileprivate var architectView: UIView!
    fileprivate var panArchitectView: UIView!
    fileprivate var peekArchitectView: UIView!
    fileprivate var peekLabel: UILabel!
    fileprivate var panView: UIPanGestureRecognizer!

    fileprivate let peekViewHeight: CGFloat = 140

    fileprivate var selectedEvent: Event?

    fileprivate var cardShowing: Bool = false
    fileprivate var peekShowing: Bool = false

    /*
    override func statusBarStyle() -> UIStatusBarStyle {
        return cardShowing ? .lightContent : .default
    }
    */

    override func navigationBarHidden() -> Bool {
        return true
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "eventSegue" {
            let dvc = segue.destination as! EventViewController
            dvc.event = selectedEvent!
        }
    }

    func initUI() {
        mapView = MGLMapView(frame: view.bounds)
        mapView.styleURL = (UIColor.theme == .light) ? URL(string: mbThemeLight)! : URL(string: mbThemeDark)!
        mapView.showsUserLocation = true
        mapView.userTrackingMode = .none
        mapView.delegate = self
        mapView.setCenter(CLLocationCoordinate2D(latitude: 34, longitude: -118), zoomLevel: 5, animated: false)
        view.addSubview(mapView)
        mapView.snp.makeConstraints { (make) in
            make.edges.equalTo(view)
        }

        //architect view (for intercepting touch)
        architectView = UIView(frame: self.view.bounds)
        let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(EventMapViewController.handleTap(gestureRecognizer:)))
        gestureRecognizer.delegate = self
        architectView.addGestureRecognizer(gestureRecognizer)
        architectView.isHidden = true
        view.addSubview(architectView)

        statusBarView = UIView()
        statusBarView.backgroundColor = UIColor.clear
        view.addSubview(statusBarView)
        statusBarView.snp.makeConstraints { (make) in
            make.left.right.top.equalTo(0)
            make.height.equalTo(20)
        }

        searchButton = UIButton()
        searchButton.backgroundColor = UIColor.kuLightBackground
        searchButton.tintColor = (UIColor.theme == .light) ? UIColor.kuPrimary : UIColor.kuDeselected
        searchButton.setImage(#imageLiteral(resourceName: "icon_search_white").withRenderingMode(.alwaysTemplate), for: .normal)
        searchButton.layer.cornerRadius = 25
        searchButton.layer.borderColor = UIColor.kuExtraLightBackground.cgColor
        searchButton.layer.borderWidth = 1
        searchButton.addTarget(self, action: #selector(searchButtonTapped(_:)), for: .touchUpInside)
        view.addSubview(searchButton)
        searchButton.snp.makeConstraints { (make) in
            make.width.height.equalTo(50)
            make.left.equalTo(24)
            make.top.equalTo(34)
        }

        filterButton = UIButton()
        filterButton.backgroundColor = UIColor.kuLightBackground
        filterButton.tintColor = (UIColor.theme == .light) ? UIColor.kuPrimary : UIColor.kuDeselected
        filterButton.setImage(#imageLiteral(resourceName: "icon_filter_white").withRenderingMode(.alwaysTemplate), for: .normal)
        filterButton.layer.cornerRadius = 20
        filterButton.layer.borderColor = UIColor.kuExtraLightBackground.cgColor
        filterButton.layer.borderWidth = 1
        filterButton.addTarget(self, action: #selector(filterButtonTapped(_:)), for: .touchUpInside)
        view.addSubview(filterButton)
        filterButton.snp.makeConstraints { (make) in
            make.width.height.equalTo(40)
            make.left.equalTo(80)
            make.top.equalTo(40)
        }

        //peek view
        peekView = UIView(frame: CGRect(x: 0, y: UIScreen.main.bounds.height, width: UIScreen.main.bounds.width, height: peekViewHeight))
        peekView.backgroundColor = UIColor(white: 1, alpha: 0.5)
        peekView.layer.cornerRadius = 10
        view.addSubview(peekView)

        //peek label
        peekLabel = UILabel(frame: CGRect(x: 0, y: 12, width: UIScreen.main.bounds.width, height: 68))
        peekLabel.font = UIFont.kuBoldFont(ofSize: 38)
        peekLabel.textColor = .black
        peekLabel.textAlignment = .center
        peekView.addSubview(peekLabel)

        //peek architect
        peekArchitectView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: peekViewHeight))
        let peekGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(EventMapViewController.peekSelected(gestureRecognizer:)))
        peekGestureRecognizer.delegate = self
        peekArchitectView.addGestureRecognizer(peekGestureRecognizer)
        peekView.addSubview(peekArchitectView)

        loadEventAnnotations()
    }

    func enterPeekView() {
        guard !peekShowing else { return }

        architectView.isHidden = false
        peekLabel.text = "\(selectedEvent!.title!) >"

        peekView.cheetah
            .move(0, peekViewHeight * -1)
            .duration(0.18)
            .easeOutExpo
            .run()

        peekShowing = true
    }

    func exitPeekView() {
        guard peekShowing else { return }

        architectView.isHidden = true
        peekView.cheetah
            .move(0, peekViewHeight)
            .duration(0.18)
            .easeInExpo
            .run()

        peekShowing = false
    }

    func loadEventAnnotations() {
        RealmManager.shared.defaultRealm.objects(Event.self).forEach { (event) in

            let annotation = EventAnnotation()
            annotation.event = event
            mapView.addAnnotation(annotation)
        }
    }

    func searchButtonTapped(_ sender: UIButton) {
        let eventSearchCardViewController = EventSearchCardViewController()
        eventSearchCardViewController.delegate = self
        UIApplication.rootViewController()?.presentCardViewController(eventSearchCardViewController)
    }

    func filterButtonTapped(_ sender: UIButton) {
        let eventFilterCardViewController = EventFilterCardViewController()
        eventFilterCardViewController.delegate = self
        UIApplication.rootViewController()?.presentCardViewController(eventFilterCardViewController)
    }
}

extension EventMapViewController: CardViewControllerDelegate {

    func cardViewControllerWillAppear(cardViewController: CardViewController) {
        cardShowing = true
        setNeedsStatusBarAppearanceUpdate()
    }

    func cardViewControllerWillDisappear(cardViewController: CardViewController) {
        cardShowing = false
        setNeedsStatusBarAppearanceUpdate()
    }
}

extension EventMapViewController: MGLMapViewDelegate {

    func mapView(_ mapView: MGLMapView, didSelect annotation: MGLAnnotation) {

        guard let eventAnnotation = annotation as? EventAnnotation else {
            return
        }

        selectedEvent = eventAnnotation.event

        enterPeekView()
    }

    func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
        return false
    }

    func mapView(_ mapView: MGLMapView, imageFor annotation: MGLAnnotation) -> MGLAnnotationImage? {
        var annotationImage = mapView.dequeueReusableAnnotationImage(withIdentifier: UIColor.kuMarkerName)

        if annotationImage == nil {
            var image = UIImage(named: UIColor.kuMarkerName)!
            image = image.withAlignmentRectInsets(UIEdgeInsets(top: 0, left: 0, bottom: image.size.height/2, right: 0))
            annotationImage = MGLAnnotationImage(image: image, reuseIdentifier: UIColor.kuMarkerName)
        }

        return annotationImage
    }
}

extension EventMapViewController: UIGestureRecognizerDelegate {

    func handleTap(gestureRecognizer: UIGestureRecognizer) {
        //close peek and keyboard on tap
        view.endEditing(true)

        if peekShowing {
            exitPeekView()
        }
    }

    func peekSelected(gestureRecognizer: UIGestureRecognizer) {
//        performSegue(withIdentifier: "eventSegue", sender: nil)

        let eventController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "EventViewController") as! EventViewController
        self.navigationController?.pushViewController(eventController, animated: true)
    }
}

Body:
To use multiple gestures make your class a GestureRecognizer delegate UIGestureRecoginizerDelegate then use this function:

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
        if (gestureRecognizer is UIPanGestureRecognizer || gestureRecognizer is UITapGestureRecognizer) {
            return true
        } else {
            return false
        }
    }


问:
Making a template with Flask
Trying to run a static html with FLask. I keep getting the error: TemplateNotFound: lucky.html

Ive examined another post similar at: Flask Template Not found however it did not help my problem. I have tried to move the templates directory around containing the lucky.html file with no luck

File path:

```<code>C:\Python27\flask_practice\templates
lucky.html
lucky.py
</code>```

Python:

```<code>from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def lucky():
    return render_template('lucky.html')

if __name__ == '__main__':
    app.run()
</code>```

Html:

```<code><html>
    <body>

        <p> Hello there </p>
        <p> Feeling lucky </p>
        <p> 7 </p>

    </body>
</html>
</code>```

答:
It looks like your directories are not set up correctly.

In my flask app, i'm using the following (project_folder/__init__.py):

```<code>app = Flask(__name__)

my_loader = jinja2.ChoiceLoader([
    app.jinja_loader,
    jinja2.FileSystemLoader(app.config["TEMPLATEDIR"]),
])
app.jinja_loader = my_loader
</code>```

with TEMPLATEDIR = "templates".

My project looks like:

```<code>root
    project_folder/__init__.py
    templates/404.html
</code>```

Title: Making a template with Flask

Body:
Trying to run a static html with FLask. I keep getting the error: TemplateNotFound: lucky.html

Ive examined another post similar at: Flask Template Not found however it did not help my problem. I have tried to move the templates directory around containing the lucky.html file with no luck

File path:

C:\Python27\flask_practice\templates
lucky.html
lucky.py

Python:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def lucky():
    return render_template('lucky.html')

if __name__ == '__main__':
    app.run()

Html:

 Hello there

 Feeling lucky

 7

Body:
It looks like your directories are not set up correctly.

In my flask app, i'm using the following (project_folder/__init__.py):

app = Flask(__name__)

my_loader = jinja2.ChoiceLoader([
    app.jinja_loader,
    jinja2.FileSystemLoader(app.config["TEMPLATEDIR"]),
])
app.jinja_loader = my_loader

with TEMPLATEDIR = "templates".

My project looks like:

root
    project_folder/__init__.py
    templates/404.html