问:
Manual Scroll with Tkinter leaving last element
I've written this piece of code with intention of making something similar to Excel, where you can scroll up and down in a spreadsheet. I have found, however, that when you scroll back up, that it leaves the lowest cell instead of scrolling it. I can't seem to figure out where I went wrong, any help is appreciated.</p>

```<code>from tkinter import *

def scroll(event): #changes from what element to start drawing

    global starting_value
    starting_value -= event.delta/120

    draw_list(starting_value)

def draw_list(starting_value): #draws entries from specified index
    for index,i in enumerate(list_of_numbers[starting_value:starting_value+10]):
        i.grid(row=index)

list_of_numbers = [Entry() for i in range(100)]

for index,i in enumerate(list_of_numbers):
    i.insert(0,index)
    i.bind('<MouseWheel>',scroll)

starting_value = 0

draw_list(starting_value)

mainloop()
</code>```

答:
Every time you scroll, any items that are no longer supposed to be visible are left in their original grid positions: you have perhaps placed new items at the same row/column, but that doesn't actually remove the original items from the grid.  You'd need something like this at the top of draw_list() to explicitly un-grid the old items:

```<code>for widget in container.grid_slaves():
    widget.grid_forget()
</code>```

Where container is the window or Frame containing your scrolling items - your example code does not actually give this object a name, you would need to do something like container = Tk() so that you can refer to it.

Body:
I've written this piece of code with intention of making something similar to Excel, where you can scroll up and down in a spreadsheet. I have found, however, that when you scroll back up, that it leaves the lowest cell instead of scrolling it. I can't seem to figure out where I went wrong, any help is appreciated.

from tkinter import *

def scroll(event): #changes from what element to start drawing

    global starting_value
    starting_value -= event.delta/120

    draw_list(starting_value)

def draw_list(starting_value): #draws entries from specified index
    for index,i in enumerate(list_of_numbers[starting_value:starting_value+10]):
        i.grid(row=index)

list_of_numbers = [Entry() for i in range(100)]

for index,i in enumerate(list_of_numbers):
    i.insert(0,index)
    i.bind('<MouseWheel>',scroll)

starting_value = 0

draw_list(starting_value)

mainloop()

Body:
Every time you scroll, any items that are no longer supposed to be visible are left in their original grid positions: you have perhaps placed new items at the same row/column, but that doesn't actually remove the original items from the grid.  You'd need something like this at the top of draw_list() to explicitly un-grid the old items:

for widget in container.grid_slaves():
    widget.grid_forget()

Where container is the window or Frame containing your scrolling items - your example code does not actually give this object a name, you would need to do something like container = Tk() so that you can refer to it.


来源: stackexchange

问:
Deploying Jenkins Artifact Built by Another Job
I installed the Deploy Plugin on my Jenkins in order to automate the deployment of my Maven built war packages to Tomcat 7. The problem is that I am able to use the plugin to deploy to a remote Tomcat server only if they are made within the same job that uses the deploy plugin. In other words, I have not been able to set up a standalone job that deploys artifacts made by a different job.

For example, I have a job named pack.foo. It uses the source code in /var/lib/project/module to create module.war and put it in /var/lib/project/module/target. However, because of the Maven version setup, the artifact posted on pack.foo's artifact page is something like module-2.0.0-SNAPSHOT.war.

The only way I am able to deploy module.war is if I add a Post-build Action to pack.foo and specify **/module.war to be a remote Tomcat manager URL (provided I have the manager's credentials in Jenkins config). Then the job's console output logs that /var/lib/project/module/target/module.war was deployed to that URL:

```<code>Deploying /var/lib/project/module/target/module.war to container Tomcat 7.x Remote with context
  [/var/lib/project/module/target/module.war] is not deployed. Doing a fresh deployment.
  Deploying [/var/lib/project/module/target/module.war]
</code>```

How can I use this, or another plugin, to deploy a WAR artifact that was made in a separate Jenkins job? I would like to have separate jobs for artifact creation and deployment. The plugin wasn't finding **/module-2.0.0-SNAPSHOT.war or even **/module.war built by another job even though there was definitely a file on disk that matched that pattern.

答:
See the paragraph on the Deploy Plugin's page you linked:

How to rollback or redeploy a previous build

There may be several ways to accomplish this, but here is one suggested method:

Install the Copy Artifact Plugin

Create a new job that you will trigger manually only when needed

Configure this job with a build parameter of type "Build selector for Copy Artifact", and a copy artifact build step using "Specified by build parameter" to select the build.

Add a post-build action to deploy the artifact that was copied from the other job

Now when you trigger this job you can enter the build number (or use any other available selector) to select which build to redeploy. Thanks to Helge Taubert for this idea.

ContentLicense: CC BY-SA 3.0

Body:
I installed the Deploy Plugin on my Jenkins in order to automate the deployment of my Maven built war packages to Tomcat 7. The problem is that I am able to use the plugin to deploy to a remote Tomcat server only if they are made within the same job that uses the deploy plugin. In other words, I have not been able to set up a standalone job that deploys artifacts made by a different job.

For example, I have a job named pack.foo. It uses the source code in /var/lib/project/module to create module.war and put it in /var/lib/project/module/target. However, because of the Maven version setup, the artifact posted on pack.foo's artifact page is something like module-2.0.0-SNAPSHOT.war.

The only way I am able to deploy module.war is if I add a Post-build Action to pack.foo and specify **/module.war to be a remote Tomcat manager URL (provided I have the manager's credentials in Jenkins config). Then the job's console output logs that /var/lib/project/module/target/module.war was deployed to that URL:

Deploying /var/lib/project/module/target/module.war to container Tomcat 7.x Remote with context
  [/var/lib/project/module/target/module.war] is not deployed. Doing a fresh deployment.
  Deploying [/var/lib/project/module/target/module.war]

How can I use this, or another plugin, to deploy a WAR artifact that was made in a separate Jenkins job? I would like to have separate jobs for artifact creation and deployment. The plugin wasn't finding **/module-2.0.0-SNAPSHOT.war or even **/module.war built by another job even though there was definitely a file on disk that matched that pattern.


问:
Firebase messaging, where to get Server Key?
Firebase allows us to send notification messages via our own application by making POST request.

This tutorial, gives to us instructions how to make this request. However, there is Authorization field in header where I must to place my own Server key.

Where I can get this Server key? There are no instructions for this.

答:
There are two keys on firebase, the first one is in Settings (Tab General)
and its call Web API Key.

The second one and in what you are interesting for is in Settings (Tab Cloud Messaging) its called Server key

Use the second one for push notifications from php.


问:
Where is my web traffic coming from?
I run a webapp created in Rails, for years it worked just fine. Then for the last couple of days it would be down at 9:50am, 10:50am, etc

I get the feeling that I'm being hammered by another site and but I have no way of checking. How do I see where my web traffic is coming from? How do I see if a large portion of it is coming from a particular IP, or a particular person, etc?

I run Debian, Rails, Lighttpd, mysql

答: The best approach is to (as mentioned above), review the web server logs, likely in /var/log/lighttpd.</p>

ContentLicense: CC BY-SA 2.5

Title: Where is my web traffic coming from?


问:
Why is this code not making a grid of raindrops?
So, I need help with Pygame for Python 3.6. This is my first semester taking a programming class and, yeah, it's a homework assignment I need help with. I had the code working when my raindrops were static, but once I put movement in for some reason it only loads one row of them now. I need a grid of raindrops that move down the screen and loads a new row each time the bottom row disappears off the screen. And yes, there's probably an easier way than having all these modules, but that's how the book wants it done. Here's what I've got so far:
raindropgame.py

```<code>import sys
import pygame
from pygame.sprite import Group
from settings import Settings
from raindrop import Raindrop
import game_functions as gf

def run_game():
    # Initialize game and create a screen object.
    pygame.init()
    settings = Settings()
    screen = pygame.display.set_mode((settings.screen_width,
settings.screen_height))
    pygame.display.set_caption("13-3")

    # Make raindrop group.
    raindrops = Group()

    # Create the raindrops.
    gf.create_raindrops(settings, screen, raindrops)

    # Start the main loop for the game.
    while True:

        gf.update_raindrops(raindrops)
        gf.update_screen(settings, screen, raindrops)

        # Watch for keyboard and mouse events.
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

run_game()
</code>```

settings.py

```<code>class Settings():
    """A class to store all settings."""

    def __init__(self):
        """Initialize the game's settings."""
        # Screen settings
        self.screen_width = 1200
        self.screen_height = 800
        self.bg_color = (0, 0, 255)

        # Raindrop settings
        self.raindrop_speed_factor = 1
</code>```

game_functions.py

```<code>import sys
import pygame
from raindrop import Raindrop

def update_screen(settings, screen, raindrops):
    """Update images on the screen and flip to the new screen."""
    # Redraw the screen during each pass through the loop.
    screen.fill(settings.bg_color)
    raindrops.draw(screen)

    # Make the most recently drawn screen visible.
    pygame.display.flip()

def get_number_raindrops_x(settings, raindrop_width):
    """Determine the number of raindrops that fit in a row."""
    available_space_x = settings.screen_width - 2 * raindrop_width
    number_raindrops_x = int(available_space_x / (2 * raindrop_width))
    return number_raindrops_x

def get_number_rows(settings, raindrop_height):
    """Determine the number of rows of raindrops that fit on the screen."""
    available_space_y = settings.screen_height - (2 * raindrop_height)
    number_rows = int(available_space_y / (2 * raindrop_height))
    return number_rows

def create_raindrop(settings, screen, raindrops, raindrop_number, row_number):
    """Create a raindrop and place it in the row."""
    raindrop = Raindrop(settings, screen)
    raindrop_width = raindrop.rect.width
    raindrop.x = raindrop_width + 2 * raindrop_width * raindrop_number
    raindrop.rect.x = raindrop.x
    raindrop.rect.y = raindrop.rect.height + 2 * raindrop.rect.height * row_number
    raindrops.add(raindrop)

def create_raindrops(settings, screen, raindrops):
    """Create a full sky of raindrops."""
    # Create a raindrop and find the number of raindrops in a row.
    raindrop = Raindrop(settings, screen)
    number_raindrops_x = get_number_raindrops_x(settings, raindrop.rect.width)
    number_rows = get_number_rows(settings, raindrop.rect.height)

    # Create the full sky of raindrops.
    for row_number in range(number_rows):
        for raindrop_number in range(number_raindrops_x):
            create_raindrop(settings, screen, raindrops, raindrop_number, row_number)

def update_raindrops(raindrops):
    """Update the positions of all raindrops in sky."""
    raindrops.update()
</code>```

raindrop.py

```<code>import pygame
from pygame.sprite import Sprite

class Raindrop(Sprite):
    """A class to represent a single raindrop in the sky."""

    def __init__(self, settings, screen):
        """Initialize the raindrop and set its starting position."""
        super(Raindrop, self).__init__()
        self.screen = screen
        self.settings = settings

        # Load the raindrop image and set its rect attribute.
        self.image = pygame.image.load('images/raindrop.png')
        self.rect = self.image.get_rect()

        # Start each new raindrop near the top left of the screen.
        self.rect.x = self.rect.width
        self.rect.y = self.rect.height

        self.y = float(self.rect.y)

    def update(self):
        """Move raindrop down."""
        self.y += self.settings.raindrop_speed_factor
        self.rect.y = self.y

    def blitme(self):
        """Draw the raindrop at its current location."""
        self.screen.blit(self.image, self.rect)
</code>```

Can anyone tell me what I've done wrong, and perhaps how to make it create a new row upon the bottom row leaving, 'cause I have no idea. :/

答:
In Raindrop.update() you have to check position and change it.

If it leaves screen on the bottom

```<code>  if self.rect.y >= self.setting.screen_height:
</code>```

then you have to move it to the top

```<code>  self.rect.y = 0
</code>```

or

```<code>  self.rect.top = 0
</code>```

Or you can move event above top border

```<code>  self.rect.bottom = 0
</code>```

```<code>def update(self):
    """Move raindrop down."""
    self.y += self.settings.raindrop_speed_factor

    # if it leaves bottom border
    if self.y >= self.settings.screen_height:
        # then put above top border
        self.y = -self.rect.height

    self.rect.y = self.y
</code>```

I would be good to create two rows above top row. At start they will be outside screen but when you move down then the they will fill top row before you move bottom row to the top.

```<code># Create the full sky of raindrops.
for row_number in range(-2, number_rows):
</code>```

Body:
So, I need help with Pygame for Python 3.6. This is my first semester taking a programming class and, yeah, it's a homework assignment I need help with. I had the code working when my raindrops were static, but once I put movement in for some reason it only loads one row of them now. I need a grid of raindrops that move down the screen and loads a new row each time the bottom row disappears off the screen. And yes, there's probably an easier way than having all these modules, but that's how the book wants it done. Here's what I've got so far:
raindropgame.py

import sys
import pygame
from pygame.sprite import Group
from settings import Settings
from raindrop import Raindrop
import game_functions as gf

def run_game():
    # Initialize game and create a screen object.
    pygame.init()
    settings = Settings()
    screen = pygame.display.set_mode((settings.screen_width,
settings.screen_height))
    pygame.display.set_caption("13-3")

    # Make raindrop group.
    raindrops = Group()

    # Create the raindrops.
    gf.create_raindrops(settings, screen, raindrops)

    # Start the main loop for the game.
    while True:

        gf.update_raindrops(raindrops)
        gf.update_screen(settings, screen, raindrops)

        # Watch for keyboard and mouse events.
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

run_game()

settings.py

class Settings():
    """A class to store all settings."""

    def __init__(self):
        """Initialize the game's settings."""
        # Screen settings
        self.screen_width = 1200
        self.screen_height = 800
        self.bg_color = (0, 0, 255)

        # Raindrop settings
        self.raindrop_speed_factor = 1

game_functions.py

import sys
import pygame
from raindrop import Raindrop

def update_screen(settings, screen, raindrops):
    """Update images on the screen and flip to the new screen."""
    # Redraw the screen during each pass through the loop.
    screen.fill(settings.bg_color)
    raindrops.draw(screen)

    # Make the most recently drawn screen visible.
    pygame.display.flip()

def get_number_raindrops_x(settings, raindrop_width):
    """Determine the number of raindrops that fit in a row."""
    available_space_x = settings.screen_width - 2 * raindrop_width
    number_raindrops_x = int(available_space_x / (2 * raindrop_width))
    return number_raindrops_x

def get_number_rows(settings, raindrop_height):
    """Determine the number of rows of raindrops that fit on the screen."""
    available_space_y = settings.screen_height - (2 * raindrop_height)
    number_rows = int(available_space_y / (2 * raindrop_height))
    return number_rows

def create_raindrop(settings, screen, raindrops, raindrop_number, row_number):
    """Create a raindrop and place it in the row."""
    raindrop = Raindrop(settings, screen)
    raindrop_width = raindrop.rect.width
    raindrop.x = raindrop_width + 2 * raindrop_width * raindrop_number
    raindrop.rect.x = raindrop.x
    raindrop.rect.y = raindrop.rect.height + 2 * raindrop.rect.height * row_number
    raindrops.add(raindrop)

def create_raindrops(settings, screen, raindrops):
    """Create a full sky of raindrops."""
    # Create a raindrop and find the number of raindrops in a row.
    raindrop = Raindrop(settings, screen)
    number_raindrops_x = get_number_raindrops_x(settings, raindrop.rect.width)
    number_rows = get_number_rows(settings, raindrop.rect.height)

    # Create the full sky of raindrops.
    for row_number in range(number_rows):
        for raindrop_number in range(number_raindrops_x):
            create_raindrop(settings, screen, raindrops, raindrop_number, row_number)

def update_raindrops(raindrops):
    """Update the positions of all raindrops in sky."""
    raindrops.update()

raindrop.py

import pygame
from pygame.sprite import Sprite

class Raindrop(Sprite):
    """A class to represent a single raindrop in the sky."""

    def __init__(self, settings, screen):
        """Initialize the raindrop and set its starting position."""
        super(Raindrop, self).__init__()
        self.screen = screen
        self.settings = settings

        # Load the raindrop image and set its rect attribute.
        self.image = pygame.image.load('images/raindrop.png')
        self.rect = self.image.get_rect()

        # Start each new raindrop near the top left of the screen.
        self.rect.x = self.rect.width
        self.rect.y = self.rect.height

        self.y = float(self.rect.y)

    def update(self):
        """Move raindrop down."""
        self.y += self.settings.raindrop_speed_factor
        self.rect.y = self.y

    def blitme(self):
        """Draw the raindrop at its current location."""
        self.screen.blit(self.image, self.rect)

Can anyone tell me what I've done wrong, and perhaps how to make it create a new row upon the bottom row leaving, 'cause I have no idea. :/

Body:
In Raindrop.update() you have to check position and change it.

If it leaves screen on the bottom

  if self.rect.y >= self.setting.screen_height:

then you have to move it to the top

  self.rect.y = 0

or

  self.rect.top = 0

Or you can move event above top border

  self.rect.bottom = 0

def update(self):
    """Move raindrop down."""
    self.y += self.settings.raindrop_speed_factor

    # if it leaves bottom border
    if self.y >= self.settings.screen_height:
        # then put above top border
        self.y = -self.rect.height

    self.rect.y = self.y

I would be good to create two rows above top row. At start they will be outside screen but when you move down then the they will fill top row before you move bottom row to the top.

# Create the full sky of raindrops.
for row_number in range(-2, number_rows):

ContentLicense: CC BY-SA 4.0


问:
Recommended way to import web components in Django templates?
Google's Polymer relies on HTML imports like this:

```<code><link rel="import" href="../components/core-header-panel/core-header-panel.html">
</code>```

Right now I'm keeping all the custom web components in the static folder and loading them like this:

template.html

```<code><link rel="import" href="{% static 'polymer/my-custom-element.html' %}">
</code>```

In the web component I import things using paths relative to the file:

my-custom-element.html

```<code><link rel="import" href="../bower_components/polymer/polymer.html">
</code>```

Is this the recommended way to import web components when using Django or is there a better way?

答:
Use django-bower (https://github.com/nvbn/django-bower), importing its also bit tricky cause 'static' in django template will add all import url pattern, for example yours import url it must be</p>

```<code><link rel="import" href="../polymer.html">
</code>```

Body:
Google's Polymer relies on HTML imports like this:

<link rel="import" href="../components/core-header-panel/core-header-panel.html">

Right now I'm keeping all the custom web components in the static folder and loading them like this:

template.html

<link rel="import" href="{% static 'polymer/my-custom-element.html' %}">

In the web component I import things using paths relative to the file:

my-custom-element.html

<link rel="import" href="../bower_components/polymer/polymer.html">

Is this the recommended way to import web components when using Django or is there a better way?

Body:
Use django-bower (https://github.com/nvbn/django-bower), importing its also bit tricky cause 'static' in django template will add all import url pattern, for example yours import url it must be

<link rel="import" href="../polymer.html">


问:
Type class constraints in type signature inside an instance when the type is a free variable
How can I add type class constraints in type signature inside an instance when the type is a free variable in Haskell. For example:

```<code>{-# LANGUAGE InstanceSigs #-}

class Pair a where
    pair :: a -> b -> (a, b)

instance Pair Int where
    pair :: (Show a) => a -> b -> (a, b)
    pair a b = (a, b)
</code>```

works, 'a' is a bound type variable whereas:

```<code>{-# LANGUAGE InstanceSigs #-}

class Pair a where
    pair :: a -> b -> (a, b)

instance Pair Int where
    pair :: (Show b) => a -> b -> (a, b)
    pair a b = (a, b)
</code>```

gives this error:

```<code>source_file.hs:8:13:
    No instance for (Show b)
    Possible fix:
      add (Show b) to the context of
        the type signature for pair :: Int -> b -> (Int, b)
    When checking that: forall a b. Show b => a -> b -> (a, b)
      is more polymorphic than: forall b. Int -> b -> (Int, b)
    When checking that instance signature for ‘pair’
      is more general than its signature in the class
      Instance sig: forall a b. Show b => a -> b -> (a, b)
         Class sig: forall b. Int -> b -> (Int, b)
    In the instance declaration for ‘Pair Int’
</code>```

答:
At the conceptual-intuitive level, the class Pair is a promise to the consumer. It says "there is this function pair, which will work for this type a and any other type b". Anybody who sees the class can use the function with any type b.

But your instance is trying to say "I'll implement this function pair, but only for bs which have a Show instance". Well, this is not a complete implementation of the class: the class promises to work for any b, but the instance works only for some bs.

Body:
How can I add type class constraints in type signature inside an instance when the type is a free variable in Haskell. For example:

{-# LANGUAGE InstanceSigs #-}

class Pair a where
    pair :: a -> b -> (a, b)

instance Pair Int where
    pair :: (Show a) => a -> b -> (a, b)
    pair a b = (a, b)

works, 'a' is a bound type variable whereas:

{-# LANGUAGE InstanceSigs #-}

class Pair a where
    pair :: a -> b -> (a, b)

instance Pair Int where
    pair :: (Show b) => a -> b -> (a, b)
    pair a b = (a, b)

gives this error:

source_file.hs:8:13:
    No instance for (Show b)
    Possible fix:
      add (Show b) to the context of
        the type signature for pair :: Int -> b -> (Int, b)
    When checking that: forall a b. Show b => a -> b -> (a, b)
      is more polymorphic than: forall b. Int -> b -> (Int, b)
    When checking that instance signature for ‘pair’
      is more general than its signature in the class
      Instance sig: forall a b. Show b => a -> b -> (a, b)
         Class sig: forall b. Int -> b -> (Int, b)
    In the instance declaration for ‘Pair Int’


问:
Same string is stored in all elements of array
I'm trying to save different strings into an array of char* but for some reason it saves the same string into every element of the array even though I am storing different strings to the elements.

```<code>char string[99];
char line[99];
FILE* out = fopen("data.out", "w");
char *words[999];
int wcount = 0;

 while(fscanf(fpointer, "%s", string) != EOF)
{
    if((strlen(string) + strlen(line))-1 <= number)
    {
        strcat(line, string);
        char word[99];
        strcpy(word, string);
        words[wcount] = word;
        printf("should have saved %s at %d\n", word, wcount);
        wcount++;

        if(strlen(line) < number)
        {
            strcat(line, " ");
        }
        puts(line);
    }
    else
    {
        fprintf(out,"%s", line);
        fprintf(out, "\n");
        strcpy(line, string);
        strcat(line, " ");
    }
}

fprintf(out, "%s", line);

printf("wcount is %d\n", wcount);
puts(words[0]);
puts(words[1]);
puts(words[2]);
</code>```

The print statement that starts with "should have saved" prints the correct string that should be saved into the words array but the print statements at the end show that the last word stored is in every element of the array.

答:
Maybe you want something like this?
Can't test it right now.</p>

```<code> char **words = NULL;
 while(fscanf(fpointer, "%s", string) != EOF)
{
    if((strlen(string) + strlen(line))-1 <= number)
    {
        strcat(line, string);
        words = realloc(words,sizeof(char *)*(wcount+1));
        words[wcount] = malloc(sizeof(char)*(strlen(string)+1));
        strcpy(words[wcount], string);
        printf("should have saved %s at %d\n", words[wcount], wcount);
        wcount++;

        if(strlen(line) < number)
        {
            strcat(line, " ");
        }
        puts(line);
    }
    else
    {
        fprintf(out,"%s", line);
        fprintf(out, "\n");
        strcpy(line, string);
        strcat(line, " ");
    }
}

fprintf(out, "%s", line);

printf("wcount is %d\n", wcount);
puts(words[0]);
puts(words[1]);
puts(words[2]);
</code>```

Body:
I'm trying to save different strings into an array of char* but for some reason it saves the same string into every element of the array even though I am storing different strings to the elements.

char string[99];
char line[99];
FILE* out = fopen("data.out", "w");
char *words[999];
int wcount = 0;

 while(fscanf(fpointer, "%s", string) != EOF)
{
    if((strlen(string) + strlen(line))-1 <= number)
    {
        strcat(line, string);
        char word[99];
        strcpy(word, string);
        words[wcount] = word;
        printf("should have saved %s at %d\n", word, wcount);
        wcount++;

        if(strlen(line) < number)
        {
            strcat(line, " ");
        }
        puts(line);
    }
    else
    {
        fprintf(out,"%s", line);
        fprintf(out, "\n");
        strcpy(line, string);
        strcat(line, " ");
    }
}

fprintf(out, "%s", line);

printf("wcount is %d\n", wcount);
puts(words[0]);
puts(words[1]);
puts(words[2]);

The print statement that starts with "should have saved" prints the correct string that should be saved into the words array but the print statements at the end show that the last word stored is in every element of the array.

Body:
Maybe you want something like this?
Can't test it right now.

 char **words = NULL;
 while(fscanf(fpointer, "%s", string) != EOF)
{
    if((strlen(string) + strlen(line))-1 <= number)
    {
        strcat(line, string);
        words = realloc(words,sizeof(char *)*(wcount+1));
        words[wcount] = malloc(sizeof(char)*(strlen(string)+1));
        strcpy(words[wcount], string);
        printf("should have saved %s at %d\n", words[wcount], wcount);
        wcount++;

        if(strlen(line) < number)
        {
            strcat(line, " ");
        }
        puts(line);
    }
    else
    {
        fprintf(out,"%s", line);
        fprintf(out, "\n");
        strcpy(line, string);
        strcat(line, " ");
    }
}

fprintf(out, "%s", line);

printf("wcount is %d\n", wcount);
puts(words[0]);
puts(words[1]);
puts(words[2]);


问:
How to modify plugins Dart code Flutter?
I am developing a Flutter app, and it uses map_view plugin. I want to add new functionalities to the plugin by modifying the source code. How do I find the actual source code of the plugin in my project after installing it through Flutter?

How plugin is added in Flutter

The dependency for map_view plugin is added to pubspec.yaml as below, then running flutter packages get will add it to the project.
           dev_dependecies:
              map_view:

答:
With the git reposity of the desired plugin here

Clone it.

Make your modification

Submit a pull request.

And done


问:
Why isn't Vue.js updating a child component?
I am using a child component for my header/navbar. This child component is named Header.vue.
I am importing it from the App.vue component like this:

```<code><template>
  <div id="app" class="container">
    <navbar></navbar>
  </div>
</template>

 <script>
 import navbar from './Header.vue'

   export default {
  name: 'app',
  firebase: {
    items: itemsRef
  },

  data () {
    return {
      newItem: {
        title: '',
        author: '',
        year: ''
      }
    }
  },
components: {
    navbar
    }
  </script>
</code>```

My child component (Header.vue) script goes like this:

```<code><template>
    <nav class="navbar navbar-default navbar-fixed-top">
        <form class="navbar-form navbar-left" role="search">
            <div class="form-group">
            <input type="text" class="form-control" placeholder="Search">
            </div>
            <button type="submit" class="btn btn-default">Submit</button>
        </form>
        <div class="navbar-right test">
            <a href="#">
            <span class="glyphicon glyphicon-shopping-cart"></span>
            </a>
            <button type="button" class="btn btn-default navbar-btn">Sign in</button>
        </div>
    </nav>
</template>

<script>
export default {
  name: 'navbar',
  data () {
    return {
      username: 'joao'
    }
  }
}

</script>
</code>```

The main component updates but the Header.vue doesn't.
It was working just fine but now it seems to be stuck at an earlier version of my header.vue component and it doesn't update. I am using webpack and npm run dev from the terminal to start the server. I have tried cleaning my cache with no results. I am just starting with vue.js so I am puzzled.
Am I doing something wrong?

答: I think I have figured it out. Wrong path to the child component... so I changed from import navbar from './components/Header.vue' to import navbar from './Header.vue' and it's working. I was weird it was showing an older version of my file though. Can't really understand why it was doing that.

Body:
I am using a child component for my header/navbar. This child component is named Header.vue.
I am importing it from the App.vue component like this:

<template>

    <navbar></navbar>

</template>

My child component (Header.vue) script goes like this:

<template>

        <form class="navbar-form navbar-left" role="search">

            <input type="text" class="form-control" placeholder="Search">

            <button type="submit" class="btn btn-default">Submit</button>
        </form>

            <button type="button" class="btn btn-default navbar-btn">Sign in</button>

</template>

The main component updates but the Header.vue doesn't.
It was working just fine but now it seems to be stuck at an earlier version of my header.vue component and it doesn't update. I am using webpack and npm run dev from the terminal to start the server. I have tried cleaning my cache with no results. I am just starting with vue.js so I am puzzled.
Am I doing something wrong?


问:
Stack exchange oauth response unreadable
Hello I am trying to set up an authorization oauth client based on Java and apache Oltu library for stack exchange api.

The response i received looks like this when printed in console
      u��n�0���"+���tU��l��*k��lۄ��{BԨM����s�h�W�#��ڇWj@ٹ�F*P�����������N��р���=ѹ�\k��

In browser the response is nicely printed in READABLE format. My problem is exactly similar as
Http request to stackexchange api returns unreadable json
but as the accepted answer suggests the response stream is gziped JSON. When I try to unzip the response my program says "Not in GZIP format" format. I tried following:
new GZIPInputStream(response)

If i convert the response to hex i get the following:

0x1FEFBFBD080000000000040075EFBFBDEFBFBD6EEFBFBD3010EFBFBD5FEFBFBDEFBFBD222B140CEFBFBDEFBFBDEFBFBD7455EFBFBDEFBFBD6CEFBFBDEFBFBD2A6BEFBFBD07EFBFBD156C13DB84EFBFBDEFBFBD7B0742D4A84DEFBFBDEFBFBDEFBFBDEFBFBD73EFBFBD68EFBFBD57EFBFBD23EFBFBDEFBFBDDA8757EFBFBD086A40D9B9EFBFBD462A50EFBFBDEFBFBDEFBFBDEFBFBDEFBFBD1216EFBFBDEFBFBDEFBFBDEFBFBDEFBFBD3C61EFBFBD1B1505D78441EFBFBDDF95EFBFBDEFBFBDCE8B2627EFBFBDEFBFBD4433EFBFBD6E45EFBFBDEFBFBD610CEFBFBDEFBFBD1142EFBFBDEFBFBD29EFBFBD6B545241EFBFBD44455EEFBFBD4DEFBFBD45797052EFBFBD10EFBFBD69C99B42E49C8BEFBFBD79EFBFBDEFBFBD08513B2BEFBFBD0B58EFBFBDEFBFBD22EFBFBDEFBFBDEFBFBD33EFBFBD3CEFBFBDEFBFBDEFBFBDEFBFBDEFBFBDEFBFBD71365EEFBFBD600BEFBFBDEFBFBD1748EFBFBDEFBFBD0F616DEFBFBDEFBFBDEFBFBDEFBFBDDBB5EFBFBD7321442EEFBFBD66EFBFBD3C07EFBFBD32EFBFBD13EFBFBDEFBFBD6BD0813CEFBFBD6207EFBFBD1756EFBFBDCDA9EFBFBDEFBFBD2DEFBFBD14EFBFBDEFBFBD35EFBFBD6D1BEFBFBD3B66EFBFBD1FEFBFBDEFBFBDEFBFBDEFBFBD1D7A0376EFBFBDEFBFBD515BEFBFBDEFBFBD2E314EEFBFBD4DEFBFBD10EFBFBD7B72EFBFBD30EFBFBDEFBFBDEFBFBDCE9974EFBFBD0FE9A1BD67474CCD9377EFBFBD1E516A03037E5059EFBFBDEFBFBD76EFBFBDEFBFBD0211EFBFBD2EEFBFBD16EFBFBD45EFBFBDEFBFBDEFBFBDEFBFBD2EEFBFBD38EFBFBD42EFBFBD05EFBFBD725E6156EFBFBDE9B1A8EFBFBDEFBFBD7B38677973EFBFBDEFBFBD5AEFBFBDEFBFBDEFBFBD73EFBFBDC69FEFBFBDEFBFBD68EFBFBDEFBFBD611A61EFBFBD16EFBFBD36E8A38DEFBFBDCF845D20EFBFBD4BEFBFBDEFBFBDEFBFBDEFBFBD797611EFBFBDEFBFBD5FEFBFBD164EEFBFBDEFBFBDD180EFBFBDEFBFBD0EEFBFBD3DD1B9EFBFBD015C1A6BEFBFBDEFBFBD020000

So my issue now is that I can not read the JSON directly and can not unzip it using GZIP. What can I do now to process the data? Any ideas ? Thank you for your time.

答:
As of now I wrote a direct http call like this                                                                               // HTTP GET request
    private String sendGet(String accessToken) throws Exception {</p>

```<code>    String url = "https://api.stackexchange.com/2.2/me?site=stackoverflow&key="key"((&access_token=";
    url = url + accessToken;
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("GET");
    int responseCode = con.getResponseCode();
    if(responseCode == 200){
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);
        //System.out.println(con.getContentEncoding());
        //System.out.println(con.getContentType());

        GZIPInputStream gp = new GZIPInputStream(con.getInputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(gp));

        StringBuffer response = new StringBuffer();
        String line;
        while ((line = br.readLine()) != null) {
            response.append(line);
        }

        br.close();

        System.out.println(response.toString());
        return response.toString();
    }
    else{
        return null;
    }
</code>```

Body:
As of now I wrote a direct http call like this                                                                               // HTTP GET request
    private String sendGet(String accessToken) throws Exception {

    String url = "https://api.stackexchange.com/2.2/me?site=stackoverflow&key="key"((&access_token=";
    url = url + accessToken;
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    con.setRequestMethod("GET");
    int responseCode = con.getResponseCode();
    if(responseCode == 200){
        System.out.println("\nSending 'GET' request to URL : " + url);
        System.out.println("Response Code : " + responseCode);
        //System.out.println(con.getContentEncoding());
        //System.out.println(con.getContentType());

        GZIPInputStream gp = new GZIPInputStream(con.getInputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(gp));

        StringBuffer response = new StringBuffer();
        String line;
        while ((line = br.readLine()) != null) {
            response.append(line);
        }

        br.close();

        System.out.println(response.toString());
        return response.toString();
    }
    else{
        return null;
    }


问:
What exactly is it Xamarin.android.support.v7.appcompat
I'm working with Xamarin.Android.
Appcompat is actually necessary for use material design because the nougat package (Android.support.design) requires it.
But why, for example, if I work only with API 27, I must add the AppCompat package? In my toolBox i've not the floatingActionButton, NavigationDrawer etc.. so I must add this packet to unlock them.
What is exactly this package? I've read on the web that this package works with backward compatibility but I only work with new APIs, so why I must install it?
Thanks.

答:
The Xamarin.Android.AppCompat is just what it says.  Its a library for App Compatibility for backward compatibility for previous versions of Android and more specifically this version (v7) brings support for Action Bar support.  Read more here :
AppCompat</p>


问:
How to use babel with npm package that will be used by react
Trying to do what I thought was a simple thing.

I have a node package that uses advanced js syntax. I want to depend on it in a react project.

So I installed babel packages via --save-dev, and added a .babelrc:

```<code>{
  "presets": ["env"],
  "plugins": ["transform-object-rest-spread"]
}
</code>```

That was not enough so I added an npm script under install to trigger the compilation. Then I had to include the compiled target lib/index.js as my entry point via main. So in the end my package.json looks something like this:

```<code>{
  "name": "bla",
  "version": "1.0.0",
  "scripts": {
    "postinstall": "babel src --out-dir lib"
  },
  "main": "lib/index.js",
  "dependencies": {},
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react-native": "^4.0.0"
  }
}
</code>```

When I run npm install locally on this project, it builds properly. However when react scripts build this (the dep is from github), I get an error: sh: 1: babel: not found.

Why is this so difficult? What am I doing wrong?

答:
sh: 1: babel: not found is from your shell not finding the babel binary file (normally under ./node_modules/.bin/babel)

You'd want to compile before you publish to npm, so anyone who installs your package has the built files. But, for Github try something like:

"postinstall": "npx babel src --out-dir lib"

Body:
Trying to do what I thought was a simple thing.

I have a node package that uses advanced js syntax. I want to depend on it in a react project.

So I installed babel packages via --save-dev, and added a .babelrc:

{
  "presets": ["env"],
  "plugins": ["transform-object-rest-spread"]
}

That was not enough so I added an npm script under install to trigger the compilation. Then I had to include the compiled target lib/index.js as my entry point via main. So in the end my package.json looks something like this:

{
  "name": "bla",
  "version": "1.0.0",
  "scripts": {
    "postinstall": "babel src --out-dir lib"
  },
  "main": "lib/index.js",
  "dependencies": {},
  "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-plugin-transform-object-rest-spread": "^6.26.0",
    "babel-preset-env": "^1.6.1",
    "babel-preset-react-native": "^4.0.0"
  }
}

When I run npm install locally on this project, it builds properly. However when react scripts build this (the dep is from github), I get an error: sh: 1: babel: not found.

Why is this so difficult? What am I doing wrong?


问:
unset while command if is empty
i have a while command after mysql and give me a row but if row is empty i get error 'Undefined variable' code is:

```<code>$m_list = mysql_query("SELECT
    t2.name,
    t2.group
    FROM tbl_m_list t1, tbl_mn_list t2
    WHERE t1.user_id = '$uid' AND
    t1.name       = t2.name    AND
    t1.group  = t2.group" );

while ($mrow = mysql_fetch_assoc($m_list)) {
    $mname[] =$mrow['name'];
    $group[] =$mrow['group'];
}
</code>```

and this is number 2 command for calling first command:

```<code><?php for ($i = 0; $i < count($mname); $i++) {?>
    <div >
        <div >
            <span >job</span>
            <span >name:</span>
            <div ><?php    echo  $mname[$i] ?>          </div>
            <span >daste:</span>
            <div ><?php    echo  $group[$i] ?>      </div>
        </div>
    </div>
<?php }?>
</code>```

give me 'Undefined variable'error for line 4 from command 2
"mname"
thanks

答:
The variables need to be defined in order to prevent the notice from occurring, otherwise, the variable is only set if mysql_fetch_assoc returns any data.

Basic solution

Before the while loop, define them, like so:

```<code>$mname = array();
$group = array();

while ($mrow = mysql_fetch_assoc($m_list)) {
// ...
</code>```

Better solution

Use the while loop instead using another loop and storing the data in two other variables. This is a cleaner solution as you're not iterating over the data twice.

```<code>while ($mrow = mysql_fetch_assoc($m_list)) { ?>
<div ><div ><span >job</span>
        <span >name:</span>
            <div ><?php    echo  $mrow['name'] ?>          </div>
        <span >daste:</span>
            <div ><?php    echo  $mrow['group'] ?>      </div>
    </div></div>
<?php } ?>
</code>```

Note: Try to refactor this code so that you aren't using mysql_* functions (use PDO or mysqli instead), as they have been removed from PHP7 and onwards.

Title: unset while command if is empty

Body:
i have a while command after mysql and give me a row but if row is empty i get error 'Undefined variable' code is:

$m_list = mysql_query("SELECT
    t2.name,
    t2.group
    FROM tbl_m_list t1, tbl_mn_list t2
    WHERE t1.user_id = '$uid' AND
    t1.name       = t2.name    AND
    t1.group  = t2.group" );

while ($mrow = mysql_fetch_assoc($m_list)) {
    $mname[] =$mrow['name'];
    $group[] =$mrow['group'];
}

and this is number 2 command for calling first command:

<?php for ($i = 0; $i < count($mname); $i++) {?>

            job
            name:

<?php    echo  $mname[$i] ?>

            daste:

<?php    echo  $group[$i] ?>

<?php }?>

give me 'Undefined variable'error for line 4 from command 2
"mname"
thanks

Body:
The variables need to be defined in order to prevent the notice from occurring, otherwise, the variable is only set if mysql_fetch_assoc returns any data.

Basic solution

Before the while loop, define them, like so:

$mname = array();
$group = array();

while ($mrow = mysql_fetch_assoc($m_list)) {
// ...

Better solution

Use the while loop instead using another loop and storing the data in two other variables. This is a cleaner solution as you're not iterating over the data twice.

while ($mrow = mysql_fetch_assoc($m_list)) { ?>
<div ><div ><span >job</span>
        <span >name:</span>
            <div ><?php    echo  $mrow['name'] ?>          </div>
        <span >daste:</span>
            <div ><?php    echo  $mrow['group'] ?>      </div>
    </div></div>
<?php } ?>

Note: Try to refactor this code so that you aren't using mysql_* functions (use PDO or mysqli instead), as they have been removed from PHP7 and onwards.


问:
TypeScript AMD to single file on browser
I'm using TypeScript and compiling it into one file to ES5 with AMD module using grunt.

For example I have app.ts :

```<code>import {CONFIG} from './config';
console.log(CONFIG.app)
</code>```

And config.ts :

```<code> export const CONFIG = {
    app      : 'MyApp'
}
</code>```

App is the main script that needs to be executed eventually, and my build output is the following :

```<code>define("config", ["require", "exports"], function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CONFIG = {
        app: 'MyApp'
    };
});
define("main", ["require", "exports", "config"], function (require, exports, config_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    console.log(config_1.CONFIG.app);
});
</code>```

How am I supposed to make it runnable on a browser ?

I've tried to include require.js but have not suceeded in doing so.

I need to compile it to a single file and all the configurations need to be on the gruntfile.js becuase it will be a large scale project that will be served as a single file.

Also, is there a more efficient way that doesn't require a third party library to compile it all into one file ?

答:
How am I supposed to make it runnable on a browser ?

You need to use the require.js runtime. AMD requires an AMD loader, require.js is the most popular option.

More

Docs http://requirejs.org/docs/start.html

Personal

Personally I would just use commonjs with webpack : https://basarat.gitbooks.io/typescript/content/docs/quick/browser.html

Body:
I'm using TypeScript and compiling it into one file to ES5 with AMD module using grunt.

For example I have app.ts :

import {CONFIG} from './config';
console.log(CONFIG.app)

And config.ts :

 export const CONFIG = {
    app      : 'MyApp'
}

App is the main script that needs to be executed eventually, and my build output is the following :

define("config", ["require", "exports"], function (require, exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CONFIG = {
        app: 'MyApp'
    };
});
define("main", ["require", "exports", "config"], function (require, exports, config_1) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    console.log(config_1.CONFIG.app);
});

How am I supposed to make it runnable on a browser ?

I've tried to include require.js but have not suceeded in doing so.

I need to compile it to a single file and all the configurations need to be on the gruntfile.js becuase it will be a large scale project that will be served as a single file.

Also, is there a more efficient way that doesn't require a third party library to compile it all into one file ?


问:
Does VS 2017 support break point debugging of node.js typescript code of a merged file?
I'm working on VS 2015 and debugging a node.js typescript app that merges all my typescript files into a single JS file.

Whenever I start debugging my node.js project, VS 2015 tells me that debugging merged JS files in typescript is not supported yet. This means i have to add breakpoints to the original JS file when debugging, as opposed to using the original typescript files.

I was wondering if 2017 has that scenario enabled now. I don't want to have to deal with the hassle of upgrading to 2017 just to find out that i still can't debug merged typescript files in node.js with VS 2017.

Any insights from anyone?

答: Finally updated to VS 2017. Turns out sadly that the answer is no. </p>


问:
Generate jHipster standalone server app without security
My understanding is that it is not possible to generate a jHipster app without any security, as is also mentioned here.

I generated a server app (using jHipster version 4.9.0) using the following command by selecting the default JWT security:

```<code>jhipster --skip-client --with-entities --skip-user-management
</code>```

However, upon running above app, I can call my GET api's directly (from a rest client such as postman or even directly from the browser), without providing any Authorization header (aka the JWT token). Essentially, security is disabled.

Could this be a bug? What am I missing here? Can someone please shed some light on what's going on?

答:
Yes it's a bug, SecurityConfiguration.java has not been generated because of wrong logic, see https://github.com/jhipster/generator-jhipster/blob/master/generators/server/files.js#L257

```<code>        /* Skip the code below for --skip-user-management */
        if (this.skipUserManagement && (this.applicationType !== 'monolith' || this.authenticationType !== 'oauth2')) return;
</code>```

Please report it on github.

Body:
My understanding is that it is not possible to generate a jHipster app without any security, as is also mentioned here.

I generated a server app (using jHipster version 4.9.0) using the following command by selecting the default JWT security:

jhipster --skip-client --with-entities --skip-user-management

However, upon running above app, I can call my GET api's directly (from a rest client such as postman or even directly from the browser), without providing any Authorization header (aka the JWT token). Essentially, security is disabled.

Could this be a bug? What am I missing here? Can someone please shed some light on what's going on?

Body:
Yes it's a bug, SecurityConfiguration.java has not been generated because of wrong logic, see https://github.com/jhipster/generator-jhipster/blob/master/generators/server/files.js#L257

        /* Skip the code below for --skip-user-management */
        if (this.skipUserManagement && (this.applicationType !== 'monolith' || this.authenticationType !== 'oauth2')) return;

Please report it on github.


问:
In a Jquery each loop containing elements with different attribute value, why does jquery load event keep firing even with logic to stop it firing
The following code only hits the load logic once per element, but the load event keeps firing previous load calls?

It loads a dynamic url for each unique element.  My results are similar to this

```<code>Element1
<Br>
Result1
Result1
Result1

Element2
<br>
Result2
Result2

Element3
<br>
Result3

.....
</code>```

If I keep scrolling down the it adds another load call to the previous so

```<code>Element1   would be...<br>
Result1
Result1
Result1
Result1
</code>```

and so on with each of the other elements

How do I only fire it once per element?

```<code>$(window).scroll(function () {

    var shouldBreakLoop = false;
    $("[mediagrid*='mediagrid']").each(function () {
        var mediaGrid = $(this).attr("mediagrid");

        if ($('#' + mediaGrid).length < 1 && is_on_screen($(this))) {

            if ($('#' + mediaGrid).length < 1) {
                $(this).empty();
                $(this).unbind('load').load(mediaGrid.split("--")[1],
                    function (responseTxt, statusTxt, xhr) {
                        if (statusTxt == "success") {
                        }
                    });

                $('<input>').attr({
                    type: 'hidden',
                    id: mediaGrid,
                    name: mediaGrid
                }).appendTo('form');

                shouldBreakLoop = true;
            }

        } else {

        }

        if (shouldBreakLoop) {
            return false;
        }
    });

});

function is_on_screen(elem) {

    var win = $(window);

    var viewport = {
        top: win.scrollTop(),
        left: win.scrollLeft()
    };
    viewport.right = viewport.left + win.width();
    viewport.bottom = viewport.top + win.height();

    var bounds = elem.offset();
    bounds.right = bounds.left + elem.outerWidth();
    bounds.bottom = bounds.top + elem.outerHeight();

    return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));

};
</code>```

答:
Add a class to the items that were already picked by ajax.</p>

```<code>$(window).scroll(function () {

    $("[mediagrid*='mediagrid']").each(function () {
        var mediaGrid = $(this).attr("mediagrid");

        if ($('#' + mediaGrid).length < 1 && is_on_screen($(this)) && !$(this).hasClass('parsed')) {

                $(this).addClass('parsed');

                $(this).load(mediaGrid.split("--")[1],
                    function (responseTxt, statusTxt, xhr) {
                        if (statusTxt == "success") {
                        }
                    });

                $('<input>').attr({
                    type: 'hidden',
                    id: mediaGrid,
                    name: mediaGrid
                }).appendTo('form');

        }
    });

});
</code>```

Body:
The following code only hits the load logic once per element, but the load event keeps firing previous load calls?

It loads a dynamic url for each unique element.  My results are similar to this

Element1

Result1
Result1
Result1

Element2

Result2
Result2

Element3

Result3

.....

If I keep scrolling down the it adds another load call to the previous so

Element1   would be...

Result1
Result1
Result1
Result1

and so on with each of the other elements

How do I only fire it once per element?

$(window).scroll(function () {

    var shouldBreakLoop = false;
    $("[mediagrid*='mediagrid']").each(function () {
        var mediaGrid = $(this).attr("mediagrid");

        if ($('#' + mediaGrid).length < 1 && is_on_screen($(this))) {

            if ($('#' + mediaGrid).length < 1) {
                $(this).empty();
                $(this).unbind('load').load(mediaGrid.split("--")[1],
                    function (responseTxt, statusTxt, xhr) {
                        if (statusTxt == "success") {
                        }
                    });

                $('<input>').attr({
                    type: 'hidden',
                    id: mediaGrid,
                    name: mediaGrid
                }).appendTo('form');

                shouldBreakLoop = true;
            }

        } else {

        }

        if (shouldBreakLoop) {
            return false;
        }
    });

});

function is_on_screen(elem) {

    var win = $(window);

    var viewport = {
        top: win.scrollTop(),
        left: win.scrollLeft()
    };
    viewport.right = viewport.left + win.width();
    viewport.bottom = viewport.top + win.height();

    var bounds = elem.offset();
    bounds.right = bounds.left + elem.outerWidth();
    bounds.bottom = bounds.top + elem.outerHeight();

    return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));

};

Body:
Add a class to the items that were already picked by ajax.

$(window).scroll(function () {

    $("[mediagrid*='mediagrid']").each(function () {
        var mediaGrid = $(this).attr("mediagrid");

        if ($('#' + mediaGrid).length < 1 && is_on_screen($(this)) && !$(this).hasClass('parsed')) {

                $(this).addClass('parsed');

                $(this).load(mediaGrid.split("--")[1],
                    function (responseTxt, statusTxt, xhr) {
                        if (statusTxt == "success") {
                        }
                    });

                $('<input>').attr({
                    type: 'hidden',
                    id: mediaGrid,
                    name: mediaGrid
                }).appendTo('form');

        }
    });

});


答:
In create_raindrop(), you need to change:

```<code>raindrop.rect.y = raindrop.rect.height + 2 * raindrop.rect.height * row_number
</code>```

to:

```<code>raindrop.y = raindrop.rect.height + 2 * raindrop.rect.height * row_number
raindrop.rect.y = raindrop.y
</code>```

Title: Why is this code not making a grid of raindrops?

Body:
So, I need help with Pygame for Python 3.6. This is my first semester taking a programming class and, yeah, it's a homework assignment I need help with. I had the code working when my raindrops were static, but once I put movement in for some reason it only loads one row of them now. I need a grid of raindrops that move down the screen and loads a new row each time the bottom row disappears off the screen. And yes, there's probably an easier way than having all these modules, but that's how the book wants it done. Here's what I've got so far:
raindropgame.py

import sys
import pygame
from pygame.sprite import Group
from settings import Settings
from raindrop import Raindrop
import game_functions as gf

def run_game():
    # Initialize game and create a screen object.
    pygame.init()
    settings = Settings()
    screen = pygame.display.set_mode((settings.screen_width,
settings.screen_height))
    pygame.display.set_caption("13-3")

    # Make raindrop group.
    raindrops = Group()

    # Create the raindrops.
    gf.create_raindrops(settings, screen, raindrops)

    # Start the main loop for the game.
    while True:

        gf.update_raindrops(raindrops)
        gf.update_screen(settings, screen, raindrops)

        # Watch for keyboard and mouse events.
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()

run_game()

settings.py

class Settings():
    """A class to store all settings."""

    def __init__(self):
        """Initialize the game's settings."""
        # Screen settings
        self.screen_width = 1200
        self.screen_height = 800
        self.bg_color = (0, 0, 255)

        # Raindrop settings
        self.raindrop_speed_factor = 1

game_functions.py

import sys
import pygame
from raindrop import Raindrop

def update_screen(settings, screen, raindrops):
    """Update images on the screen and flip to the new screen."""
    # Redraw the screen during each pass through the loop.
    screen.fill(settings.bg_color)
    raindrops.draw(screen)

    # Make the most recently drawn screen visible.
    pygame.display.flip()

def get_number_raindrops_x(settings, raindrop_width):
    """Determine the number of raindrops that fit in a row."""
    available_space_x = settings.screen_width - 2 * raindrop_width
    number_raindrops_x = int(available_space_x / (2 * raindrop_width))
    return number_raindrops_x

def get_number_rows(settings, raindrop_height):
    """Determine the number of rows of raindrops that fit on the screen."""
    available_space_y = settings.screen_height - (2 * raindrop_height)
    number_rows = int(available_space_y / (2 * raindrop_height))
    return number_rows

def create_raindrop(settings, screen, raindrops, raindrop_number, row_number):
    """Create a raindrop and place it in the row."""
    raindrop = Raindrop(settings, screen)
    raindrop_width = raindrop.rect.width
    raindrop.x = raindrop_width + 2 * raindrop_width * raindrop_number
    raindrop.rect.x = raindrop.x
    raindrop.rect.y = raindrop.rect.height + 2 * raindrop.rect.height * row_number
    raindrops.add(raindrop)

def create_raindrops(settings, screen, raindrops):
    """Create a full sky of raindrops."""
    # Create a raindrop and find the number of raindrops in a row.
    raindrop = Raindrop(settings, screen)
    number_raindrops_x = get_number_raindrops_x(settings, raindrop.rect.width)
    number_rows = get_number_rows(settings, raindrop.rect.height)

    # Create the full sky of raindrops.
    for row_number in range(number_rows):
        for raindrop_number in range(number_raindrops_x):
            create_raindrop(settings, screen, raindrops, raindrop_number, row_number)

def update_raindrops(raindrops):
    """Update the positions of all raindrops in sky."""
    raindrops.update()

raindrop.py

import pygame
from pygame.sprite import Sprite

class Raindrop(Sprite):
    """A class to represent a single raindrop in the sky."""

    def __init__(self, settings, screen):
        """Initialize the raindrop and set its starting position."""
        super(Raindrop, self).__init__()
        self.screen = screen
        self.settings = settings

        # Load the raindrop image and set its rect attribute.
        self.image = pygame.image.load('images/raindrop.png')
        self.rect = self.image.get_rect()

        # Start each new raindrop near the top left of the screen.
        self.rect.x = self.rect.width
        self.rect.y = self.rect.height

        self.y = float(self.rect.y)

    def update(self):
        """Move raindrop down."""
        self.y += self.settings.raindrop_speed_factor
        self.rect.y = self.y

    def blitme(self):
        """Draw the raindrop at its current location."""
        self.screen.blit(self.image, self.rect)

Can anyone tell me what I've done wrong, and perhaps how to make it create a new row upon the bottom row leaving, 'cause I have no idea. :/

Body:
In create_raindrop(), you need to change:

raindrop.rect.y = raindrop.rect.height + 2 * raindrop.rect.height * row_number

to:

raindrop.y = raindrop.rect.height + 2 * raindrop.rect.height * row_number
raindrop.rect.y = raindrop.y


问:
How can I install TypeScript declarations for scoped/namespaced packages via @types?
I'm using TypeScript and I want to use a scoped package (e.g. @foo/bar, @babel/core, etc.) that doesn't ship its own type declarations.

I've tried to run something like

```<code>npm install @types/@foo/bar
</code>```

but it doesn't seem to be available.

Is there any way to get these .d.ts for these packages into the @types scope? Is there a way to write my own scoped packages on DefinitelyTyped if I need to?

答:
Is there any way to get these .d.ts for these packages into the @types scope?

Yes there is a way! It's just a little unintuitive.

npm doesn't permit scoped packages to contain @ in their name, so these names are mangled to use two underscores in place of the @.

So as an example, if you want to install type declarations for the package @foo/bar, you'll need to run

```<code>npm install @types/foo__bar
</code>```

Is there a way to write my own scoped packages on DefinitelyTyped if I need to?

Yes! From the Definitely Typed README.md:

Types for a scoped package @foo/bar should go in types/foo__bar. Note the double underscore.

Body:
I'm using TypeScript and I want to use a scoped package (e.g. @foo/bar, @babel/core, etc.) that doesn't ship its own type declarations.

I've tried to run something like

npm install @types/@foo/bar

but it doesn't seem to be available.

Is there any way to get these .d.ts for these packages into the @types scope? Is there a way to write my own scoped packages on DefinitelyTyped if I need to?

Body:
Is there any way to get these .d.ts for these packages into the @types scope?

Yes there is a way! It's just a little unintuitive.

npm doesn't permit scoped packages to contain @ in their name, so these names are mangled to use two underscores in place of the @.

So as an example, if you want to install type declarations for the package @foo/bar, you'll need to run

npm install @types/foo__bar

Is there a way to write my own scoped packages on DefinitelyTyped if I need to?

Yes! From the Definitely Typed README.md:

Types for a scoped package @foo/bar should go in types/foo__bar. Note the double underscore.


问:
java PrintWritter or BufferedOutputStream method flush not working on windows 2012
i have problem only with Windows 2012 server.
I am trying write a big file to disk using PrintWritter or BufferedOutputStream, the problem is that in Windows 2012 when call a method flush() to send the data stream to file not is working.
Only write the data to file when close() method is called.
The problem is that the data save in memory and consumed a lot of file.
In my Windows 7 or 8 is working fine.
Some idea issued with windows 2012?
Thanks,

Simple example:

```<code>File file = new File("myFile.txt");
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(file)), "UTF-8"), 1024 * 4);
        for (int i = 0; i < 1000000; i++) {
            out.write("Some info here");
            if (i % 300 == 0) {
                out.flush();

            }
        }
        out.close();
</code>```

答:
flush() does work, even on Windows 2012. However PrintWriter does swallow exceptions: you need to check for those with checkError(). It might be better to just use the BufferedWriter.

A maximum of 4096 or 8192 characters, not sure which (or whatever you specified in the BufferedWriter), is buffered, so your memory loss is elsewhere.

Body:
i have problem only with Windows 2012 server.
I am trying write a big file to disk using PrintWritter or BufferedOutputStream, the problem is that in Windows 2012 when call a method flush() to send the data stream to file not is working.
Only write the data to file when close() method is called.
The problem is that the data save in memory and consumed a lot of file.
In my Windows 7 or 8 is working fine.
Some idea issued with windows 2012?
Thanks,

Simple example:

File file = new File("myFile.txt");
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new BufferedOutputStream(new FileOutputStream(file)), "UTF-8"), 1024 * 4);
        for (int i = 0; i < 1000000; i++) {
            out.write("Some info here");
            if (i % 300 == 0) {
                out.flush();

            }
        }
        out.close();


问:
is there an API for PHP_CodeSniffer?
Does PHP_CodeSniffer have an API I can use, rather than run the command line?

So given a string of PHP code, $code, and Composer ensuring loading of the PHP_CodeSniffer code, is there something I can do such as:

```<code>// Pseudocode!
$code_sniffer = new PHPCodeSniffer;
$result = $code_sniffer->sniff($code);
</code>```

rather than go via the command line with something like:

```<code>$result = exec(sprintf('echo %s | vendor/bin/phpcs', escapeshellarg($code)));
</code>```

答:
Here's what I got working for PHPCS 2:</p>

```<code>PHP_CodeSniffer::setConfigData(
  'installed_paths',
  // The path to the standard I am using.
  __DIR__ . '/../../vendor/drupal/coder/coder_sniffer',
  TRUE
);

$phpcs = new PHP_CodeSniffer(
  // Verbosity.
  0,
  // Tab width
  0,
  // Encoding.
  'iso-8859-1',
  // Interactive.
  FALSE
);

$phpcs->initStandard('Drupal');

// Mock a PHP_CodeSniffer_CLI object, as the PHP_CodeSniffer object expects
// to have this and be able to retrieve settings from it.
// (I am using PHPCS within tests, so I have Prophecy available to do this. In another context, just creating a subclass of PHP_CodeSniffer_CLI set to return the right things would work too.)
$prophet = new \Prophecy\Prophet;
$prophecy = $prophet->prophesize();
$prophecy->willExtend(\PHP_CodeSniffer_CLI::class);
// No way to set these on the phpcs object.
$prophecy->getCommandLineValues()->willReturn([
  'reports' => [
    "full" => NULL,
  ],
  "showSources" => false,
  "reportWidth" => null,
  "reportFile" => null
]);
$phpcs_cli = $prophecy->reveal();
// Have to set these properties, as they are read directly, e.g. by
// PHP_CodeSniffer_File::_addError()
$phpcs_cli->errorSeverity = 5;
$phpcs_cli->warningSeverity = 5;

// Set the CLI object on the PHP_CodeSniffer object.
$phpcs->setCli($phpcs_cli);

// Process the file with PHPCS.
$phpcsFile = $phpcs->processFile(NULL, $code);

$errors   = $phpcsFile->getErrorCount();
$warnings = $phpcsFile->getWarningCount();

$total_error_count = ($phpcsFile->getErrorCount() + $phpcsFile->getWarningCount());

// Get the reporting to process the errors.
$this->reporting = new \PHP_CodeSniffer_Reporting();
$reportClass = $this->reporting->factory('full');

// This gets you an array of all the messages which you can easily work over.
$reportData  = $this->reporting->prepareFileReport($phpcsFile);

// This formats the report, but prints it directly.
$reportClass->generateFileReport($reportData, $phpcsFile);
</code>```

Title: is there an API for PHP_CodeSniffer?

Body:
Does PHP_CodeSniffer have an API I can use, rather than run the command line?

So given a string of PHP code, $code, and Composer ensuring loading of the PHP_CodeSniffer code, is there something I can do such as:

// Pseudocode!
$code_sniffer = new PHPCodeSniffer;
$result = $code_sniffer->sniff($code);

rather than go via the command line with something like:

$result = exec(sprintf('echo %s | vendor/bin/phpcs', escapeshellarg($code)));

Body:
Here's what I got working for PHPCS 2:

PHP_CodeSniffer::setConfigData(
  'installed_paths',
  // The path to the standard I am using.
  __DIR__ . '/../../vendor/drupal/coder/coder_sniffer',
  TRUE
);

$phpcs = new PHP_CodeSniffer(
  // Verbosity.
  0,
  // Tab width
  0,
  // Encoding.
  'iso-8859-1',
  // Interactive.
  FALSE
);

$phpcs->initStandard('Drupal');

// Mock a PHP_CodeSniffer_CLI object, as the PHP_CodeSniffer object expects
// to have this and be able to retrieve settings from it.
// (I am using PHPCS within tests, so I have Prophecy available to do this. In another context, just creating a subclass of PHP_CodeSniffer_CLI set to return the right things would work too.)
$prophet = new \Prophecy\Prophet;
$prophecy = $prophet->prophesize();
$prophecy->willExtend(\PHP_CodeSniffer_CLI::class);
// No way to set these on the phpcs object.
$prophecy->getCommandLineValues()->willReturn([
  'reports' => [
    "full" => NULL,
  ],
  "showSources" => false,
  "reportWidth" => null,
  "reportFile" => null
]);
$phpcs_cli = $prophecy->reveal();
// Have to set these properties, as they are read directly, e.g. by
// PHP_CodeSniffer_File::_addError()
$phpcs_cli->errorSeverity = 5;
$phpcs_cli->warningSeverity = 5;

// Set the CLI object on the PHP_CodeSniffer object.
$phpcs->setCli($phpcs_cli);

// Process the file with PHPCS.
$phpcsFile = $phpcs->processFile(NULL, $code);

$errors   = $phpcsFile->getErrorCount();
$warnings = $phpcsFile->getWarningCount();

$total_error_count = ($phpcsFile->getErrorCount() + $phpcsFile->getWarningCount());

// Get the reporting to process the errors.
$this->reporting = new \PHP_CodeSniffer_Reporting();
$reportClass = $this->reporting->factory('full');

// This gets you an array of all the messages which you can easily work over.
$reportData  = $this->reporting->prepareFileReport($phpcsFile);

// This formats the report, but prints it directly.
$reportClass->generateFileReport($reportData, $phpcsFile);


问:
How to check a SQL CASE with multiple conditions?
I have two tables. Accounts ACC and FinancialTrans FT

The FinancialTrans table is as follows:

```<code>AcctID  TransTypeCode   DateOfTrans
123     TOLL            2016-06-06 00:00:00.000
123     TOLL            2016-06-02 00:00:00.000
123     TOLL            2016-04-28 00:00:00.000
123     PYMT            2016-03-11 00:00:00.000
123     TOLL            2015-12-22 00:00:00.000
123     TOLL            2015-12-22 00:00:00.000
</code>```

The requirement is:

When any Accounts have NO 'TOLL' or 'PYMT' in the last 2 years print 'Flag'

```<code>SELECT ACC.Field1
      ,ACC.Field2
      ,ACC.Field3
      ,ACC.Field4
      ,CASE WHEN
        (SELECT Max(DateOfTrans) FROM FinanceTrans FT
         WHERE ACC.AccountID = FT.AcctID
               AND (TransTypeCode = 'TOLL' AND DateOfTrans >= DATEADD(year, -2, GETDATE()))
               AND (TransTypeCode = 'PYMT' AND DateOfTrans >= DATEADD(year, -2, GETDATE()))
             GROUP BY AcctID, TransTypeCode) IS NULL
        THEN 'Flag'
        ELSE ''
       AND AS NoNo_Flag

FROM Accounts ACC

WHERE Condition 1, Condition 2...
</code>```

答:
You should be using window functions.  The logic is to look at the maximum date for the two transaction types.  The flag then depends on the relationship to the current date.</p>

```<code>select a.*,
       (case when max(case when transtype in ('TOLL', 'PYMT') then DateOfTrans end) over
                       (partition by acctid) >= dateadd(year, -2, getdate())
             then 0 else 1
        end) as flag
from accounts;
</code>```

Body:
I have two tables. Accounts ACC and FinancialTrans FT

The FinancialTrans table is as follows:

AcctID  TransTypeCode   DateOfTrans
123     TOLL            2016-06-06 00:00:00.000
123     TOLL            2016-06-02 00:00:00.000
123     TOLL            2016-04-28 00:00:00.000
123     PYMT            2016-03-11 00:00:00.000
123     TOLL            2015-12-22 00:00:00.000
123     TOLL            2015-12-22 00:00:00.000

The requirement is:

When any Accounts have NO 'TOLL' or 'PYMT' in the last 2 years print 'Flag'

SELECT ACC.Field1
      ,ACC.Field2
      ,ACC.Field3
      ,ACC.Field4
      ,CASE WHEN
        (SELECT Max(DateOfTrans) FROM FinanceTrans FT
         WHERE ACC.AccountID = FT.AcctID
               AND (TransTypeCode = 'TOLL' AND DateOfTrans >= DATEADD(year, -2, GETDATE()))
               AND (TransTypeCode = 'PYMT' AND DateOfTrans >= DATEADD(year, -2, GETDATE()))
             GROUP BY AcctID, TransTypeCode) IS NULL
        THEN 'Flag'
        ELSE ''
       AND AS NoNo_Flag

FROM Accounts ACC

WHERE Condition 1, Condition 2...

Body:
You should be using window functions.  The logic is to look at the maximum date for the two transaction types.  The flag then depends on the relationship to the current date.

select a.*,
       (case when max(case when transtype in ('TOLL', 'PYMT') then DateOfTrans end) over
                       (partition by acctid) >= dateadd(year, -2, getdate())
             then 0 else 1
        end) as flag
from accounts;


问:
"GSSException Defective token detected" - when trying to Authenticate to Tomcat running on Windows using Kerberos
I am struggling to authenticate to a Java web container (I've tried both Tomcat and Jetty) when running on Windows 2012.

Every time I try the Negotiate auth scheme I get an error: org.ietf.jgss.GSSException: Defective token detected (Mechanism level: GSSHeader did not find the right tag)

Steps to reproduce

Start out by setting up a Windows Server 2012 or 2016 instance and install active directory domain services.

In my example, I created:

NETBIOS Domain: NICKIS

Dns domain: nickis.life

Create the kerberos subject user on Active Directory

IMPORTANT: MAKE SURE THAT THE FIRST NAME, LAST NAME AND FULL NAME ARE THE SAME!

The new user in my case is:

DN = CN=kerberos500,CN=Users,DC=nickis,DC=life

login+domain = kerberos500@nickis.life

NETBIOS\samAccountName = NICKIS\kerberos500

Run the setspn command from the Windows Active Directory Server

```<code>setspn -A HTTP/nickis.life@NICKIS.LIFE kerberos500
</code>```

Example output:

```<code>C:\Users\Administrator>setspn -A HTTP/nickis.life kerberos500
Checking domain DC=nickis,DC=life
Registering ServicePrincipalNames for CN=kerberos500,CN=Users,DC=nickis,DC=life
        HTTP/kerberos500.nickis.life
Updated object
</code>```

Run the ktpass command from the Windows Active Directory Server

```<code>ktpass -out c:\Users\Administrator\kerberos500.keytab -princ HTTP/nickis.life@NICKIS.LIFE -mapUser kerberos500 -mapOp set -pass XXXXpasswordforkerberos500userXXXX -crypto DES-CBC-MD5 -pType KRB5_NT_PRINCIPAL +DesOnly
</code>```

Example output:

```<code>C:\Users\Administrator>ktpass -out c:\Users\Administrator\kerberos500.keytab -princ HTTP/nickis.life@NICKIS.LIFE -mapUser kerberos500 -mapOp set -pass xxxxxxxx -crypto DES-CBC-MD5 -pType KRB5_NT_PRINCIPAL +DesOnly
Targeting domain controller: WIN-OVV6VHBGIB8.nickis.life
Using legacy password setting method
Successfully mapped HTTP/kerberos500.nickis.life to kerberos500.
Key created.
Output keytab to c:\Users\Administrator\kerberos500.keytab:
Keytab version: 0x502
keysize 71 HTTP/kerberos500.nickis.life@NICKIS.LIFE ptype 1 (KRB5_NT_PRINCIPAL) vno 3 etype 0x3 (DES-CBC-MD5) keylength 8 (0xcd07200bea625d20)
Account kerberos500 has been set for DES-only encryption.
</code>```

At this point, you will now have a keytab file:

```<code>c:\Users\Administrator\kerberos500.keytab
</code>```

And a user principal:

```<code>HTTP/kerberos500.nickis.life@NICKIS.LIFE
</code>```

These are the 2 inputs that are needed to provide to the GSSApi to get single sign on with Kerberos.

So I deployed those inputs to my web container's kerberos security realm in the Hadoop security module.

Curl test I tried unsuccessfully to use curl to test it:

curl --negotiate -u : http://nickis.life:8080/my/webapp

Internet Explorer test I also tried using Internet Explorer. I added nickis.life domain to the Trusted Roles in Internet Explorer. Then I launch the site in internet explorer: http://nickis.life:8080

Either way, I get the error below:

```<code>org.apache.hadoop.security.authentication.client.AuthenticationException: GSSException: Defective token detected (Mechanism level: GSSHeader did not find the right tag)
    at org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler.authenticate(KerberosAuthenticationHandler.java:398) ~[hadoop-auth-2.7.1.jar:?]

...

Caused by: org.ietf.jgss.GSSException: Defective token detected (Mechanism level: GSSHeader did not find the right tag)
    at sun.security.jgss.GSSHeader.<init>(Unknown Source) ~[?:1.8.0_131]
    at sun.security.jgss.GSSContextImpl.acceptSecContext(Unknown Source) ~[?:1.8.0_131]
    at sun.security.jgss.GSSContextImpl.acceptSecContext(Unknown Source) ~[?:1.8.0_131]
    at org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler$2.run(KerberosAuthenticationHandler.java:365) ~[hadoop-auth-2.7.1.jar:?]
    at org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler$2.run(KerberosAuthenticationHandler.java:347) ~[hadoop-auth-2.7.1.jar:?]
    at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_131]
    at javax.security.auth.Subject.doAs(Unknown Source) ~[?:1.8.0_131]
    at org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler.authenticate(KerberosAuthenticationHandler.java:347) ~[hadoop-auth-2.7.1.jar:?]
</code>```

I am stumped. NOTE: I have found several links around here and there but none of them were all inclusive on the steps that were followed like I have summed up here, and none of the solutions provided within worked for me.

I am attempting kerberos login from a different machine on the domain than the server is running on

I have tried all sorts of combinations of keytab generation variations none have worked.

There is no duplicate SPN.

I tried setting up the DNS in the domain server as an A record.

I wonder maybe if there's some kerberos windows server setup steps and Microsoft employee verified that this should not be the case here: https://social.msdn.microsoft.com/Forums/sharepoint/en-US/db15ad96-e269-436e-952f-fe9dfb39da8a/setting-up-a-test-windows-server-active-directory-for-kerberos-testing?forum=winserverDS

Can anyone trace what I am screwing up here?

UPDATE:

I have AD server with domain set to fusionis.life, and the AD server is WIN-OVV6VHBGIB8.fusionis.life

I moved the tomcat server to another windows machine in the domain. DESKTOP-VTPBE99.fusionis.life

I opened dnsmgmt.msc and added a "Forward Lookup Zone" with "kerberos500.nickis.life" with A HOST set to the IP of the DESKTOP-VTPBE99.fusionis.life box.

I deleted the AD account, recreated it, then re-generated the keytab again as suggested in one of the answers on the ticket.

C:\Users\Administrator>ktpass -out c:\Users\Administrator\kerberos500.keytab -princ HTTP/kerberos500.nickis.life@NICKIS.LIFE -mapUser kerberos500 -mapOp set -pass xxxxxxxxx -crypto ALL -pType KRB5_NT_PRINCIPAL
Targeting domain controller: WIN-OVV6VHBGIB8.fusionis.life
Using legacy password setting method
Successfully mapped HTTP/kerberos500.nickis.life to kerberos500.
Key created.
Key created.
Key created.
Key created.
Key created.
Output keytab to c:\Users\Administrator\kerberos500.keytab:
Keytab version: 0x502
keysize 67 HTTP/kerberos500.nickis.life@NICKIS.LIFE ptype 1 (KRB5_NT_PRINCIPAL) vno 4 etype 0x1 (DES-CBC-CRC) keylength 8 (0x04e30b9183ba8389)
keysize 67 HTTP/kerberos500.nickis.life@NICKIS.LIFE ptype 1 (KRB5_NT_PRINCIPAL) vno 4 etype 0x3 (DES-CBC-MD5) keylength 8 (0x04e30b9183ba8389)
keysize 75 HTTP/kerberos500.nickis.life@NICKIS.LIFE ptype 1 (KRB5_NT_PRINCIPAL) vno 4 etype 0x17 (RC4-HMAC) keylength 16 (0xe39a141de38abd8750bf9c0bf49fd1c5)
keysize 91 HTTP/kerberos500.nickis.life@NICKIS.LIFE ptype 1 (KRB5_NT_PRINCIPAL) vno 4 etype 0x12 (AES256-SHA1) keylength 32 (0xe368a1b060cfe4816f522c1c5f62ca07fe201ed96c6d018054dfbd5b86251892)
keysize 75 HTTP/kerberos500.nickis.life@NICKIS.LIFE ptype 1 (KRB5_NT_PRINCIPAL) vno 4 etype 0x11 (AES128-SHA1) keylength 16 (0x1b1a548fa2893a78c6f4c7f9c482b614)

I saved the keytab updated file on the server, then updated the Service Principal to HTTP/kerberos500.nickis.life@NICKIS.LIFE

I logged into tomcat machine as a domain user, added http://kerberos500.nickis.life to the trusted sites, then navigated to http://kerberos500.nickis.life:8764

I checked all combinations of the encryption check boxes in the kerberos500 AD "account" tab.

Now i'm getting a new error...

GSSException: No valid credentials provided (Mechanism level: Failed to find any Kerberos credentails)

UPDATE:

Resolved finally. I got this final error because I needed fusionis.life to be on the same host as nickis.life

答:
Try this:

Solution 1

run this on windows cmd:

ksetup /addkdc
ksetup /addhosttorealmmap

and set SPNEGO settings on browser

Solution 2

try with Firefox, do this before:

1) open this URL in Firefox

about:config

2) Set this: network.negotiate-auth.trusted-uris

Set for any cluster DNS domain requiring negotiated authentication (like the kerberos enabled cluster HTTP authentication).

Example:

network.negotiate-auth.trusted-uris=.lily.cloudera.com,.solr.cloudera.com

2) Set this: network.auth.use-sspi=false
3) Restart Firefox
4) You have to download the Windows isntaller from here:

http://web.mit.edu/kerberos/dist/#kfw-4.0

5) Copy the Kerberos client configuration to here

C:\ProgramData\MIT\Kerberos5\krb5.ini

6) Create a ticket with the MIT kerberos GUI client

7) Try again with Firefox

Hope it can help.

Body:
I am struggling to authenticate to a Java web container (I've tried both Tomcat and Jetty) when running on Windows 2012.

Every time I try the Negotiate auth scheme I get an error: org.ietf.jgss.GSSException: Defective token detected (Mechanism level: GSSHeader did not find the right tag)

Steps to reproduce

Start out by setting up a Windows Server 2012 or 2016 instance and install active directory domain services.

In my example, I created:

NETBIOS Domain: NICKIS

Dns domain: nickis.life

Create the kerberos subject user on Active Directory

IMPORTANT: MAKE SURE THAT THE FIRST NAME, LAST NAME AND FULL NAME ARE THE SAME!

The new user in my case is:

DN = CN=kerberos500,CN=Users,DC=nickis,DC=life

login+domain = kerberos500@nickis.life

NETBIOS\samAccountName = NICKIS\kerberos500

Run the setspn command from the Windows Active Directory Server

setspn -A HTTP/nickis.life@NICKIS.LIFE kerberos500

Example output:

C:\Users\Administrator>setspn -A HTTP/nickis.life kerberos500
Checking domain DC=nickis,DC=life
Registering ServicePrincipalNames for CN=kerberos500,CN=Users,DC=nickis,DC=life
        HTTP/kerberos500.nickis.life
Updated object

Run the ktpass command from the Windows Active Directory Server

ktpass -out c:\Users\Administrator\kerberos500.keytab -princ HTTP/nickis.life@NICKIS.LIFE -mapUser kerberos500 -mapOp set -pass XXXXpasswordforkerberos500userXXXX -crypto DES-CBC-MD5 -pType KRB5_NT_PRINCIPAL +DesOnly

Example output:

C:\Users\Administrator>ktpass -out c:\Users\Administrator\kerberos500.keytab -princ HTTP/nickis.life@NICKIS.LIFE -mapUser kerberos500 -mapOp set -pass xxxxxxxx -crypto DES-CBC-MD5 -pType KRB5_NT_PRINCIPAL +DesOnly
Targeting domain controller: WIN-OVV6VHBGIB8.nickis.life
Using legacy password setting method
Successfully mapped HTTP/kerberos500.nickis.life to kerberos500.
Key created.
Output keytab to c:\Users\Administrator\kerberos500.keytab:
Keytab version: 0x502
keysize 71 HTTP/kerberos500.nickis.life@NICKIS.LIFE ptype 1 (KRB5_NT_PRINCIPAL) vno 3 etype 0x3 (DES-CBC-MD5) keylength 8 (0xcd07200bea625d20)
Account kerberos500 has been set for DES-only encryption.

At this point, you will now have a keytab file:

c:\Users\Administrator\kerberos500.keytab

And a user principal:

HTTP/kerberos500.nickis.life@NICKIS.LIFE

These are the 2 inputs that are needed to provide to the GSSApi to get single sign on with Kerberos.

So I deployed those inputs to my web container's kerberos security realm in the Hadoop security module.

Curl test I tried unsuccessfully to use curl to test it:

curl --negotiate -u : http://nickis.life:8080/my/webapp

Internet Explorer test I also tried using Internet Explorer. I added nickis.life domain to the Trusted Roles in Internet Explorer. Then I launch the site in internet explorer: http://nickis.life:8080

Either way, I get the error below:

org.apache.hadoop.security.authentication.client.AuthenticationException: GSSException: Defective token detected (Mechanism level: GSSHeader did not find the right tag)
    at org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler.authenticate(KerberosAuthenticationHandler.java:398) ~[hadoop-auth-2.7.1.jar:?]

...

Caused by: org.ietf.jgss.GSSException: Defective token detected (Mechanism level: GSSHeader did not find the right tag)
    at sun.security.jgss.GSSHeader.<init>(Unknown Source) ~[?:1.8.0_131]
    at sun.security.jgss.GSSContextImpl.acceptSecContext(Unknown Source) ~[?:1.8.0_131]
    at sun.security.jgss.GSSContextImpl.acceptSecContext(Unknown Source) ~[?:1.8.0_131]
    at org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler$2.run(KerberosAuthenticationHandler.java:365) ~[hadoop-auth-2.7.1.jar:?]
    at org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler$2.run(KerberosAuthenticationHandler.java:347) ~[hadoop-auth-2.7.1.jar:?]
    at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_131]
    at javax.security.auth.Subject.doAs(Unknown Source) ~[?:1.8.0_131]
    at org.apache.hadoop.security.authentication.server.KerberosAuthenticationHandler.authenticate(KerberosAuthenticationHandler.java:347) ~[hadoop-auth-2.7.1.jar:?]

I am stumped. NOTE: I have found several links around here and there but none of them were all inclusive on the steps that were followed like I have summed up here, and none of the solutions provided within worked for me.

I am attempting kerberos login from a different machine on the domain than the server is running on

I have tried all sorts of combinations of keytab generation variations none have worked.

There is no duplicate SPN.

I tried setting up the DNS in the domain server as an A record.

I wonder maybe if there's some kerberos windows server setup steps and Microsoft employee verified that this should not be the case here: https://social.msdn.microsoft.com/Forums/sharepoint/en-US/db15ad96-e269-436e-952f-fe9dfb39da8a/setting-up-a-test-windows-server-active-directory-for-kerberos-testing?forum=winserverDS

Can anyone trace what I am screwing up here?

UPDATE:

I have AD server with domain set to fusionis.life, and the AD server is WIN-OVV6VHBGIB8.fusionis.life

I moved the tomcat server to another windows machine in the domain. DESKTOP-VTPBE99.fusionis.life

I opened dnsmgmt.msc and added a "Forward Lookup Zone" with "kerberos500.nickis.life" with A HOST set to the IP of the DESKTOP-VTPBE99.fusionis.life box.

I deleted the AD account, recreated it, then re-generated the keytab again as suggested in one of the answers on the ticket.

C:\Users\Administrator>ktpass -out c:\Users\Administrator\kerberos500.keytab -princ HTTP/kerberos500.nickis.life@NICKIS.LIFE -mapUser kerberos500 -mapOp set -pass xxxxxxxxx -crypto ALL -pType KRB5_NT_PRINCIPAL
Targeting domain controller: WIN-OVV6VHBGIB8.fusionis.life
Using legacy password setting method
Successfully mapped HTTP/kerberos500.nickis.life to kerberos500.
Key created.
Key created.
Key created.
Key created.
Key created.
Output keytab to c:\Users\Administrator\kerberos500.keytab:
Keytab version: 0x502
keysize 67 HTTP/kerberos500.nickis.life@NICKIS.LIFE ptype 1 (KRB5_NT_PRINCIPAL) vno 4 etype 0x1 (DES-CBC-CRC) keylength 8 (0x04e30b9183ba8389)
keysize 67 HTTP/kerberos500.nickis.life@NICKIS.LIFE ptype 1 (KRB5_NT_PRINCIPAL) vno 4 etype 0x3 (DES-CBC-MD5) keylength 8 (0x04e30b9183ba8389)
keysize 75 HTTP/kerberos500.nickis.life@NICKIS.LIFE ptype 1 (KRB5_NT_PRINCIPAL) vno 4 etype 0x17 (RC4-HMAC) keylength 16 (0xe39a141de38abd8750bf9c0bf49fd1c5)
keysize 91 HTTP/kerberos500.nickis.life@NICKIS.LIFE ptype 1 (KRB5_NT_PRINCIPAL) vno 4 etype 0x12 (AES256-SHA1) keylength 32 (0xe368a1b060cfe4816f522c1c5f62ca07fe201ed96c6d018054dfbd5b86251892)
keysize 75 HTTP/kerberos500.nickis.life@NICKIS.LIFE ptype 1 (KRB5_NT_PRINCIPAL) vno 4 etype 0x11 (AES128-SHA1) keylength 16 (0x1b1a548fa2893a78c6f4c7f9c482b614)

I saved the keytab updated file on the server, then updated the Service Principal to HTTP/kerberos500.nickis.life@NICKIS.LIFE

I logged into tomcat machine as a domain user, added http://kerberos500.nickis.life to the trusted sites, then navigated to http://kerberos500.nickis.life:8764

I checked all combinations of the encryption check boxes in the kerberos500 AD "account" tab.

Now i'm getting a new error...

GSSException: No valid credentials provided (Mechanism level: Failed to find any Kerberos credentails)

UPDATE:

Resolved finally. I got this final error because I needed fusionis.life to be on the same host as nickis.life


问:
Prolog: searching if 2 elements in a list occur equally
I am new to Prolog and not a native speaker, so if you do not understand me,  I am sorry.

My question is how can I find if a and b from a list appears equally?

For example, [a,a,b,b] should give me true but if either one appears more than the other it should give false. ex: [a,a,a,b,b].

Can anyone help me please? This is what I have so far and I know it is wrong but I am trying.

```<code>count(N,[],0).
count(N,[N|T],U) :-
   !,
   count(N,T,U1),
   U is U1+1.
count(N,[H|T],U) :-
   count(N,T,U).

occurrences([],[]).
occurrences([H|T],[[H,X]|Y]) :-
   count(H,[H|T],X),
   occurrences(T1,Y).
</code>```

答:
You have only one list so at first your pattern matching will fail btw i will try like this and i'm not adding any explaination so that you can self figure it out how it works.</p>

```<code>count(List):-
  count(List,0,0).

count([],L,L).

count([H|T],L,R):-
  (
   H == 'a' ->
      NewL is L + 1,
      count(T,NewL,R)
    )
     ;
   (
     H == 'b' ->
       NewRight is R + 1,
       count(T,L,NewRight)
    ).
</code>```

Body:
I am new to Prolog and not a native speaker, so if you do not understand me,  I am sorry.

My question is how can I find if a and b from a list appears equally?

For example, [a,a,b,b] should give me true but if either one appears more than the other it should give false. ex: [a,a,a,b,b].

Can anyone help me please? This is what I have so far and I know it is wrong but I am trying.

count(N,[],0).
count(N,[N|T],U) :-
   !,
   count(N,T,U1),
   U is U1+1.
count(N,[H|T],U) :-
   count(N,T,U).

occurrences([],[]).
occurrences([H|T],[[H,X]|Y]) :-
   count(H,[H|T],X),
   occurrences(T1,Y).

Body:
You have only one list so at first your pattern matching will fail btw i will try like this and i'm not adding any explaination so that you can self figure it out how it works.

count(List):-
  count(List,0,0).

count([],L,L).

count([H|T],L,R):-
  (
   H == 'a' ->
      NewL is L + 1,
      count(T,NewL,R)
    )
     ;
   (
     H == 'b' ->
       NewRight is R + 1,
       count(T,L,NewRight)
    ).


问:
Including a shared library in a go build
How can I include an SO file when I build for linux? With windows I simply put the dll in the same folder but that did not work with the linux build. In particular, I am building a go sciter project and need to include the libsciter-gtk-64.so in the executable/package.

答: My way of solving this was to use an additional tool, which had the added benefit of an optional desktop file and other metadata. AppImage solves the library problem, all I had to do was create an AppImage with the so files in /usr/lib/ and build through their command.</p>


问:
How to unit test library that relies on Session object
I have several asp.net mvc websites consuming the same controller and model.

This common logic is put in seperate libraries.
These libraries use the HttpContext.Current.Session. How can I make these unit testable?
I read about the StateValue but can't completely grasp it. Where should I get this StateValue thing? Is it a lib I reference?

答:
Your code should use IHttpSessionState not HttpSessionState.

If you look up the MSDN documentation for IHttpSessionState you will find an example implementation you can lift into your Unit Test project to create a mock session.

Replace code aquiring the Session with static delegate that return IHttpSessionState.

Initialise that static delegate with a function that uses HttpContext.Current.Session.

During Unit Testing replace delegate with your Mock implementation of IHttpSessionState.

OwnerDisplayName: boris callens

OwnerDisplayName: AnthonyWJones


问:
OSError: [Errno 13] Permission denied: '/var/lib/pgadmin'
Ubuntu 16.04.3

I'd like to install pgAdmin:

I hvae created a virtualenv with python 2.

Then install pgAdmin 4 v2.0:

```<code>pip install https://ftp.postgresql.org/pub/pgadmin/pgadmin4/v2.0/pip/pgadmin4-2.0-py2.py3-none-any.whl
</code>```

It's time to run pgAdmin:

```<code>(pgadmin4) michael@michael-desktop:~/PycharmProjects/venv$ python pgadmin4/lib/python2.7/site-packages/pgadmin4/pgAdmin4.py
Traceback (most recent call last):
  File "pgadmin4/lib/python2.7/site-packages/pgadmin4/pgAdmin4.py", line 55, in <module>
    exec(open(file_quote(setupfile), 'r').read())
  File "<string>", line 46, in <module>
  File "/home/michael/PycharmProjects/venv/pgadmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/setup/data_directory.py", line 23, in create_app_data_directory
    _create_directory_if_not_exists(os.path.dirname(config.SQLITE_PATH))
  File "/home/michael/PycharmProjects/venv/pgadmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/setup/data_directory.py", line 15, in _create_directory_if_not_exists
    os.mkdir(_path)
OSError: [Errno 13] Permission denied: '/var/lib/pgadmin'
</code>```

Could you give me a kick here?

答:
create the folders manually (or add to your pgAdmin installation script, if there is one), and assign the permissions:

```<code>sudo mkdir "/var/log/pgadmin"
sudo chmod a+wrx "/var/log/pgadmin"

sudo mkdir "/var/lib/pgadmin"
sudo chmod a+wrx "/var/lib/pgadmin"
</code>```

this would not assign permissions to the entire /var/log but just for the /var/log/pgadmin only.

Body:
Ubuntu 16.04.3

I'd like to install pgAdmin:

I hvae created a virtualenv with python 2.

Then install pgAdmin 4 v2.0:

pip install https://ftp.postgresql.org/pub/pgadmin/pgadmin4/v2.0/pip/pgadmin4-2.0-py2.py3-none-any.whl

It's time to run pgAdmin:

(pgadmin4) michael@michael-desktop:~/PycharmProjects/venv$ python pgadmin4/lib/python2.7/site-packages/pgadmin4/pgAdmin4.py
Traceback (most recent call last):
  File "pgadmin4/lib/python2.7/site-packages/pgadmin4/pgAdmin4.py", line 55, in <module>
    exec(open(file_quote(setupfile), 'r').read())
  File "<string>", line 46, in <module>
  File "/home/michael/PycharmProjects/venv/pgadmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/setup/data_directory.py", line 23, in create_app_data_directory
    _create_directory_if_not_exists(os.path.dirname(config.SQLITE_PATH))
  File "/home/michael/PycharmProjects/venv/pgadmin4/lib/python2.7/site-packages/pgadmin4/pgadmin/setup/data_directory.py", line 15, in _create_directory_if_not_exists
    os.mkdir(_path)
OSError: [Errno 13] Permission denied: '/var/lib/pgadmin'

Could you give me a kick here?

Body:
create the folders manually (or add to your pgAdmin installation script, if there is one), and assign the permissions:

sudo mkdir "/var/log/pgadmin"
sudo chmod a+wrx "/var/log/pgadmin"

sudo mkdir "/var/lib/pgadmin"
sudo chmod a+wrx "/var/lib/pgadmin"

this would not assign permissions to the entire /var/log but just for the /var/log/pgadmin only.


问:
Storing Data in the correct way in Python
In Keywords.txt I have these words and their 'values':

```<code>alone,1

amazed,10

amazing,10

bad,1

best,10

better,7

excellent,10
</code>```

These are some of the keywords and their 'values' that I need to store in a data structure, a list. Each line will be later used to access/extract the word and its 'value'.

The list I made in a while loop was:

```<code>line = KeywordFile.readline()

while line != '':

   line=KeywordFile.readline()
   line = line.rstrip()
</code>```

And I tried to convert it to a list form by doing this:

```<code>   list=[line]
</code>```

However, when I print the list, I get this:

```<code>['amazed,10']
['amazing,10']
['bad,1']
['best,10']
['better,7']
['excellent,10']
</code>```

I don't think that I'll be able to extract my 'values' from the lists that easy if they are inside quotation marks.

I'm looking to get lists in this format:

```<code>['amazed',10]
['amazing',10]
['bad',1]
</code>```

Thanks in advance!

答:
You want to split the line into a list based on the string delimiter ','.

```<code>list = line.split(',')
</code>```

Then you want to convert the second value in each list into an int.

```<code>list[1] = int(list[1])
</code>```

Body:
In Keywords.txt I have these words and their 'values':

alone,1

amazed,10

amazing,10

bad,1

best,10

better,7

excellent,10

These are some of the keywords and their 'values' that I need to store in a data structure, a list. Each line will be later used to access/extract the word and its 'value'.

The list I made in a while loop was:

line = KeywordFile.readline()

while line != '':

   line=KeywordFile.readline()
   line = line.rstrip()

And I tried to convert it to a list form by doing this:

   list=[line]

However, when I print the list, I get this:

['amazed,10']
['amazing,10']
['bad,1']
['best,10']
['better,7']
['excellent,10']

I don't think that I'll be able to extract my 'values' from the lists that easy if they are inside quotation marks.

I'm looking to get lists in this format:

['amazed',10]
['amazing',10]
['bad',1]

Thanks in advance!

Body:
You want to split the line into a list based on the string delimiter ','.

list = line.split(',')

Then you want to convert the second value in each list into an int.

list[1] = int(list[1])