问:
Make sprite appear when pressing space and disappear after X seconds?
Okay, so I have a game made with pygame. The game is that there is a man at the bottom of the screen shooting up upwards the top of the screen to hit enemies. The man can move left and right.

To shoot you press space.

When you shoot I want a small sprite to appear at the end of the gun-barrel so it looks as if flames comes out like a real gun shooting.

I have managed to get the fire sprite to appear when pressing space BUT I also want the sprite to disappear after maybe 0.3 seconds (Ill adjust the time once I get it to disappear).

How do I actually do this? I feel kind of lost here

I have tried to google and look and look here at stackoverflow but I cant find what I need.

game.py

```<code># -- SNIP --

def run_game():

    # -- SNIP ---

    # Start the main loop for the game.
    while True:
        # Watch for keyboard and mouse events.
        gf.check_events(ai_settings, screen, stats, sb, play_button, man,
        enemies, bullets)

        if stats.game_active:
            man.update()
            gf.update_bullets(ai_settings, screen, stats, sb, man, enemies,
                              bullets)
            gf.update_enemies(ai_settings, stats, screen, sb, man, enemies,
                             bullets)

        gf.update_screen(ai_settings, screen, stats, sb, man, enemies,
        bullets, play_button)

run_game()
</code>```

game_functions.py

```<code>
# -- SNIP --

def check_events(ai_settings, screen, stats, sb, play_button, man, enemies,
                 bullets):
    """Respond to keypresses and mouse events."""
    # -- SNIP --
        elif event.type == pygame.KEYDOWN:
            check_keydown_events(event, ai_settings, screen, stats, sb, man,
                                 enemies, bullets)
        # -- SNIP --

def check_keydown_events(event, ai_settings, screen, stats, sb, man, enemies, bullets):
    """Respond to key presses."""
    if event.key == pygame.K_RIGHT:
        man.moving_right = True
        man.orientation = "Right"
    elif event.key == pygame.K_LEFT:
        man.moving_left = True
        man.orientation = "Left"

    # Draw sprite if space is pressed
    elif event.key == pygame.K_SPACE:
        fire_bullet(ai_settings, bullets, screen, man)
        man.fire_screen.blit(man.fire, man.fire_rect)
    # --- SNIP ---

# -- SNIP --

</code>```

man.py

```<code>class Man(Sprite):
    # -- SNIP --
        # Load the man image and get its rect.
        self.image = pygame.image.load('images/man_gun_large.bmp')
        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()

        # Gun fire sprite
        self.fire = pygame.image.load('images/fire.bmp')
        self.fire_rect = self.fire.get_rect()
        self.screen_fire_rect = self.image.get_rect()
        self.fire_screen = self.image

        self.ai_settings = ai_settings

        # Start each new man at the bottom center of the screen.
        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = self.screen_rect.bottom

        # Load the fire sprite at the end of the mans gunbarrel
        self.fire_rect.centerx = self.screen_fire_rect.left + 20
        self.fire_rect.top = self.screen_fire_rect.top

# ---SNIP---

        # Movement flags
        self.moving_right = False
        self.moving_left = False

        self.orientation = False

    def blitme(self):
        """Draw the man at its current location."""
        self.screen.blit(self.image, self.rect)
        if self.orientation == "Right":
            self.screen.blit(self.image, self.rect)
        elif self.orientation == "Left":
            self.screen.blit(pygame.transform.flip(self.image, True, False), self.rect)
</code>```

答:
Use pygame.time.get_ticks() to manage the life cycle of the bullets.

Add a list, which contains tuples of the end of life time of a bullet and the bullet itself.

bullets = []
```

<p>When a bullet spawns, then calculate the end time and append the information to the list:</p>

<pre class="lang-py prettyprint-override"><code>def check_keydown_events(event, ai_settings, screen, stats, sb, man, enemies, bullets):

    # [...]

    # Draw sprite if space is pressed
    elif event.key == pygame.K_SPACE:

        bullet = # [...]

        end_time = pygame.time.get_ticks() + 300 # 300 millisconds = 0.3 seconds
        bullets.append( (end_time, bullet) )
</code>```

Check if a bullet has reached the end of life and decide to keep the bullet or to .kill it:

current_time = pygame.time.get_ticks()
current_bullets = bullets
bullets = []
for end_time, bullet in current_bullets:
    if current_time > end_time:
        bullet.kill()
    else:
        bullets.append( (end_time, bullet) )
```

Body:
Okay, so I have a game made with pygame. The game is that there is a man at the bottom of the screen shooting up upwards the top of the screen to hit enemies. The man can move left and right.

To shoot you press space.

When you shoot I want a small sprite to appear at the end of the gun-barrel so it looks as if flames comes out like a real gun shooting.

I have managed to get the fire sprite to appear when pressing space BUT I also want the sprite to disappear after maybe 0.3 seconds (Ill adjust the time once I get it to disappear).

How do I actually do this? I feel kind of lost here

I have tried to google and look and look here at stackoverflow but I cant find what I need.

game.py

# -- SNIP --

def run_game():

    # -- SNIP ---

    # Start the main loop for the game.
    while True:
        # Watch for keyboard and mouse events.
        gf.check_events(ai_settings, screen, stats, sb, play_button, man,
        enemies, bullets)

        if stats.game_active:
            man.update()
            gf.update_bullets(ai_settings, screen, stats, sb, man, enemies,
                              bullets)
            gf.update_enemies(ai_settings, stats, screen, sb, man, enemies,
                             bullets)

        gf.update_screen(ai_settings, screen, stats, sb, man, enemies,
        bullets, play_button)

run_game()

game_functions.py

# -- SNIP --

def check_events(ai_settings, screen, stats, sb, play_button, man, enemies,
                 bullets):
    """Respond to keypresses and mouse events."""
    # -- SNIP --
        elif event.type == pygame.KEYDOWN:
            check_keydown_events(event, ai_settings, screen, stats, sb, man,
                                 enemies, bullets)
        # -- SNIP --

def check_keydown_events(event, ai_settings, screen, stats, sb, man, enemies, bullets):
    """Respond to key presses."""
    if event.key == pygame.K_RIGHT:
        man.moving_right = True
        man.orientation = "Right"
    elif event.key == pygame.K_LEFT:
        man.moving_left = True
        man.orientation = "Left"

    # Draw sprite if space is pressed
    elif event.key == pygame.K_SPACE:
        fire_bullet(ai_settings, bullets, screen, man)
        man.fire_screen.blit(man.fire, man.fire_rect)
    # --- SNIP ---

# -- SNIP --

man.py

class Man(Sprite):
    # -- SNIP --
        # Load the man image and get its rect.
        self.image = pygame.image.load('images/man_gun_large.bmp')
        self.rect = self.image.get_rect()
        self.screen_rect = screen.get_rect()

        # Gun fire sprite
        self.fire = pygame.image.load('images/fire.bmp')
        self.fire_rect = self.fire.get_rect()
        self.screen_fire_rect = self.image.get_rect()
        self.fire_screen = self.image

        self.ai_settings = ai_settings

        # Start each new man at the bottom center of the screen.
        self.rect.centerx = self.screen_rect.centerx
        self.rect.bottom = self.screen_rect.bottom

        # Load the fire sprite at the end of the mans gunbarrel
        self.fire_rect.centerx = self.screen_fire_rect.left + 20
        self.fire_rect.top = self.screen_fire_rect.top

# ---SNIP---

        # Movement flags
        self.moving_right = False
        self.moving_left = False

        self.orientation = False

    def blitme(self):
        """Draw the man at its current location."""
        self.screen.blit(self.image, self.rect)
        if self.orientation == "Right":
            self.screen.blit(self.image, self.rect)
        elif self.orientation == "Left":
            self.screen.blit(pygame.transform.flip(self.image, True, False), self.rect)

Body:
Use pygame.time.get_ticks() to manage the life cycle of the bullets.

Add a list, which contains tuples of the end of life time of a bullet and the bullet itself.

bullets = []

When a bullet spawns, then calculate the end time and append the information to the list:

def check_keydown_events(event, ai_settings, screen, stats, sb, man, enemies, bullets):

    # [...]

    # Draw sprite if space is pressed
    elif event.key == pygame.K_SPACE:

        bullet = # [...]

        end_time = pygame.time.get_ticks() + 300 # 300 millisconds = 0.3 seconds
        bullets.append( (end_time, bullet) )

Check if a bullet has reached the end of life and decide to keep the bullet or to .kill it:

current_time = pygame.time.get_ticks()
current_bullets = bullets
bullets = []
for end_time, bullet in current_bullets:
    if current_time > end_time:
        bullet.kill()
    else:
        bullets.append( (end_time, bullet) )


来源: stackexchange

问:
PHPExcel return a corrupted file
If I save it to file:

```<code>$objWriter->save("test.xls");
</code>```

And then download from server, I can open file without any problems.

But when I try to save into php://output, got corrupted file like described in this question.

I tried this:

```<code>ob_end_clean();
header( "Content-type: application/vnd.ms-excel" );
header('Content-Disposition: attachment; filename="test.xls"');
header("Pragma: no-cache");
header("Expires: 0");

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

$objWriter->save('php://output');
exit;
</code>```

ob_end_clean(); doesn't help.

I tried PHPExcel_Writer_Excel2007 and PHPExcel_Writer_Excel5. Same problem.

UPD: as I can see, excell file has BOM at start ("EF BB BF"). But I've checked all my script, they don't have BOM symbol. So, does it means that PXPExcell add BOM?

答:
User   **ob_end_clean(); **   Before u set the header

like this :

```<code>     ob_end_clean();
              header('Content-Type: application/vnd.ms-excel'); //mime type

            header("Content-Disposition: attachment; filename=\"filename.xls\"");
            header("Cache-Control: max-age=0");
            $objWriter = PHPExcel_IOFactory::createWriter($object, 'Excel5');
              $objWriter->save('php://output');
</code>```

ContentLicense: CC BY-SA 3.0

Title: PHPExcel return a corrupted file

Body:
If I save it to file:

$objWriter->save("test.xls");

And then download from server, I can open file without any problems.

But when I try to save into php://output, got corrupted file like described in this question.

I tried this:

ob_end_clean();
header( "Content-type: application/vnd.ms-excel" );
header('Content-Disposition: attachment; filename="test.xls"');
header("Pragma: no-cache");
header("Expires: 0");

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');

$objWriter->save('php://output');
exit;

ob_end_clean(); doesn't help.

I tried PHPExcel_Writer_Excel2007 and PHPExcel_Writer_Excel5. Same problem.

UPD: as I can see, excell file has BOM at start ("EF BB BF"). But I've checked all my script, they don't have BOM symbol. So, does it means that PXPExcell add BOM?

Body:
User   **ob_end_clean(); **   Before u set the header

like this :

     ob_end_clean();
              header('Content-Type: application/vnd.ms-excel'); //mime type

            header("Content-Disposition: attachment; filename=\"filename.xls\"");
            header("Cache-Control: max-age=0");
            $objWriter = PHPExcel_IOFactory::createWriter($object, 'Excel5');
              $objWriter->save('php://output');

ContentLicense: CC BY-SA 4.0


问:
Adding the last two elements of a list
In Mathematica, what is the cleanest way of taking a list

```<code>{r1, r2, r3, ..., rn, a, b}
</code>```

and returning

```<code>{r1, r2, r3, ..., rn, a + b}
</code>```

or more generally

```<code>{r1, r2, r3, ..., rn, f[a, b]}
</code>```

for some function f?

答:
I'd use rules if performance is not a big issue (lists are not packed etc):</p>

```<code> lst = {a, b, c, d, e}

 In[13]:= Replace[lst, {left__, ntl_, l_} :> {left, f[ntl, l]}, {0}]

 Out[13]= {a, b, c, f[d, e]}
</code>```

Title: Adding the last two elements of a list

Body:
In Mathematica, what is the cleanest way of taking a list

{r1, r2, r3, ..., rn, a, b}

and returning

{r1, r2, r3, ..., rn, a + b}

or more generally

{r1, r2, r3, ..., rn, f[a, b]}

for some function f?

Body:
I'd use rules if performance is not a big issue (lists are not packed etc):

 lst = {a, b, c, d, e}

 In[13]:= Replace[lst, {left__, ntl_, l_} :> {left, f[ntl, l]}, {0}]

 Out[13]= {a, b, c, f[d, e]}


问:
Cannot instantiate abstract class
I have base abastract class Employee with pure virtual method clone

```<code>virtual Employee* clone() const = 0;
</code>```

Also i have derived class DeveloperEmployee that override this method:

```<code>DeveloperEmployee* clone() const override {
        return new DeveloperEmployee(this->description, this->project);
}
</code>```

Now I have these lines in main:

```<code>DeveloperEmployee* a = new DeveloperEmployee(description, project);
DeveloperEmployee* a_copy = a->clone();
</code>```

And I cannot change these lines. It says me that I can't instantiate abstract class, so how should I change the code?

If I change overrided method to

```<code>Employee* clone() const override {
        return new DeveloperEmployee(this->description, this->project);
}
</code>```

I have cast problem in main and I cannot change main.

答:
DeveloperEmployee* clone() const override can not override virtual Employee* clone() const since the return types are different. As long as you don't override virtual Employee* clone() const you can not instantiate an instance of DeveloperEmployee since it's a pure virtual function.

DeveloperEmployee should have the following definition.

```<code>Employee* clone() const override {
        return new DeveloperEmployee(this->description, this->project);
}
</code>```

It's hard to understand what you mean by that you can't change the main, but to exploit polymorphism you would ideally create a base class pointer, assign it with the address of a derived class object and pass the pointer around.

Title: Cannot instantiate abstract class

Body:
I have base abastract class Employee with pure virtual method clone

virtual Employee* clone() const = 0;

Also i have derived class DeveloperEmployee that override this method:

DeveloperEmployee* clone() const override {
        return new DeveloperEmployee(this->description, this->project);
}

Now I have these lines in main:

DeveloperEmployee* a = new DeveloperEmployee(description, project);
DeveloperEmployee* a_copy = a->clone();

And I cannot change these lines. It says me that I can't instantiate abstract class, so how should I change the code?

If I change overrided method to

Employee* clone() const override {
        return new DeveloperEmployee(this->description, this->project);
}

I have cast problem in main and I cannot change main.

Body:
DeveloperEmployee* clone() const override can not override virtual Employee* clone() const since the return types are different. As long as you don't override virtual Employee* clone() const you can not instantiate an instance of DeveloperEmployee since it's a pure virtual function.

DeveloperEmployee should have the following definition.

Employee* clone() const override {
        return new DeveloperEmployee(this->description, this->project);
}

It's hard to understand what you mean by that you can't change the main, but to exploit polymorphism you would ideally create a base class pointer, assign it with the address of a derived class object and pass the pointer around.


问:
ApolloClient from apollo-boost attemped to assign to readonly property
I'm working with react-native, and trying to load Apollo from apollo-boost.  When I attempt to import the client, I get the error message "Attempted to assign to readonly property."  I'm not sure how to work around this, and it seems from the stack trace that it's in the apollo-boost package.  Anybody know how I can work around this?

edit:  Adding picture and details.
I'm getting this when I try to load the app through Expo.  Right when it starts, I get this.  The first file in my app the stack trace mentions, StoresScreens, the line in question is only the import line.

```<code>import ApolloClient from 'apollo-boost';
</code>```

答:
At least using Typescript, as temporary workaround you can do:

```<code>import ApolloClient from "apollo-boost/lib/index";
</code>```

Seems related with this issue: https://github.com/apollographql/apollo-client/issues/4843

Body:
I'm working with react-native, and trying to load Apollo from apollo-boost.  When I attempt to import the client, I get the error message "Attempted to assign to readonly property."  I'm not sure how to work around this, and it seems from the stack trace that it's in the apollo-boost package.  Anybody know how I can work around this?

edit:  Adding picture and details.
I'm getting this when I try to load the app through Expo.  Right when it starts, I get this.  The first file in my app the stack trace mentions, StoresScreens, the line in question is only the import line.

import ApolloClient from 'apollo-boost';

Body:
At least using Typescript, as temporary workaround you can do:

import ApolloClient from "apollo-boost/lib/index";

Seems related with this issue: https://github.com/apollographql/apollo-client/issues/4843


问:
Sum the two lowest values from a record
I have a table like this:

I need to sum the two lowest values for each record. For example, in the first row 2 and 4 (2 + 4 = 6).

I can find the lowest value for each row using CROSS APPLY, but I can't find the two lowest values at once to sum them.

Thanks in advance.

答:
```<code>SELECT
 IIF (VALUE1 < VALUE3 AND VALUE2 < VALUE3,
       VALUE1 + VALUE2,
       IIF(VALUE1 < VALUE2 AND VALUE3 < VALUE2,
        VALUE1 + VALUE3,
        IIF(VALUE3 < VALUE1 AND VALUE2 < VALUE1,
         VALUE2 + VALUE3, 0)))
</code>```

<p>-- You will have to decide what to do if none of the conditions are met: I set the result to zero. This gets unwieldy if you add more columns </p>

Title: Sum the two lowest values from a record

Body:
SELECT
 IIF (VALUE1 < VALUE3 AND VALUE2 < VALUE3,
       VALUE1 + VALUE2,
       IIF(VALUE1 < VALUE2 AND VALUE3 < VALUE2,
        VALUE1 + VALUE3,
        IIF(VALUE3 < VALUE1 AND VALUE2 < VALUE1,
         VALUE2 + VALUE3, 0)))

-- You will have to decide what to do if none of the conditions are met: I set the result to zero. This gets unwieldy if you add more columns


问:
Laravel cannot route to /admin
I'm starting a new project with Laravel 5.7. I've made standard laravel Auth with artisan. It registered a new route in routes/web.php which is

```<code>Route::get('/home', 'HomeController@index')->name('home');
</code>```

The problem is when i rename '/home' to '/admin' it doesn't work. It returns 'The requested resource /admin was not found on this server.' error.
I can replace '/home' with anything except '/admin'. Anything else works without a problem.
What is wrong with '/admin' and why can't i use '/admin' as a route?

答:
You can't use this '/admin' route because your project may have 'admin' folder (but not listing file due server config).
Simply rename your admin folder or use '/admin/home' instead.</p>

Title: Laravel cannot route to /admin

Body:
I'm starting a new project with Laravel 5.7. I've made standard laravel Auth with artisan. It registered a new route in routes/web.php which is

Route::get('/home', 'HomeController@index')->name('home');

The problem is when i rename '/home' to '/admin' it doesn't work. It returns 'The requested resource /admin was not found on this server.' error.
I can replace '/home' with anything except '/admin'. Anything else works without a problem.
What is wrong with '/admin' and why can't i use '/admin' as a route?


问:
static_cast int to reference to int?
Is it allowed:

```<code>int x = 1;
int r1 = static_cast<int&>(x);
int r2 = static_cast<int&&>(x)
</code>```

If it is, then what is the meaning of these casts?

The question has arisen from this code:

```<code>int x = 1;
int y = 2;
std::swap(x, y); // uses int temp = std::move(x);
</code>```

答:
static_cast int to reference to int?
  Is it allowed

Yes. It is allowed.

If it is, then what is the meaning of these casts?

Casting to lvalue reference of same type is mostly pointless, since a variable used by itself is already an lvalue. However, it can affect decltype deduction as shown in Ben Voigt's example. Casting to a reference to another type is useful if you need to downcast a reference to base (which is not relevant to int).

Casting to rvalue reference is useful, since it changes the type of the expression into xvalue. This allows moving from variables. This is in fact what std::move does. This doesn't make a difference with int in particular though.

Title: static_cast int to reference to int?

Body:
Is it allowed:

int x = 1;
int r1 = static_cast<int&>(x);
int r2 = static_cast<int&&>(x)

If it is, then what is the meaning of these casts?

The question has arisen from this code:

int x = 1;
int y = 2;
std::swap(x, y); // uses int temp = std::move(x);


答:
```<code>static_cast<int&>(x);
</code>```

Doesn't do anything as x is already of type int& when used in expression.

```<code>static_cast<int&&>(x);
</code>```

Casts x, an l-value, to r-value. This is exactly what std::move does and T&& are used for implementing move semantics.

std::swap uses std::move because there's simply no downside and probable performance boost. Move ctors/assignments should always be at least as efficient as copy ctors/assignments.

Title: static_cast int to reference to int?

Body:
static_cast<int&>(x);

Doesn't do anything as x is already of type int& when used in expression.

static_cast<int&&>(x);

Casts x, an l-value, to r-value. This is exactly what std::move does and T&& are used for implementing move semantics.

std::swap uses std::move because there's simply no downside and probable performance boost. Move ctors/assignments should always be at least as efficient as copy ctors/assignments.


问:
get text area and text field data - jquery
I have 2 text areas in my page as;

```<code><input type="text" id="a1"/>
<textarea id="b2"></textarea>
<a id="button">button</a>
</code>```

When user click the button link, I want to alert the data entered in a1 and b2.

How can I do this?? Here is there demo

Thanks in advance...:)

blasteralfred

答:
```<code>  $(document).ready(function() {
    $('#button').click(function(e) {
      e.preventDefault();
      alert($('#a1').val());
      alert($('#b2').val());
    });
  });
</code>```

Body:
I have 2 text areas in my page as;

<input type="text" id="a1"/>
<textarea id="b2"></textarea>
button

When user click the button link, I want to alert the data entered in a1 and b2.

How can I do this?? Here is there demo

Thanks in advance...:)

blasteralfred


问:
NameError (uninitialized constant OAuth Did you mean? OAuth2)
I'm trying to use omniauth-linkedin-oauth2 on RoR 5.0.7.

```<code>gem 'devise'
gem 'omniauth'
gem 'omniauth-oauth2'
gem 'omniauth-linkedin-oauth2'
</code>```

but I got an error on production environment and I can not start rails apps. My local developing environment is no problem to run it.

The error on production.log is

```<code>NameError (uninitialized constant OAuth Did you mean?  OAuth2)
</code>```

if I replaced

```<code>gem 'omniauth-linkedin-oauth2'
</code>```

to

```<code>gem 'omniauth-linkedin'
</code>```

and bundle update then there is no errors and RoR is running.

My production environment is

```<code>Debian GNU/Linux 8.11 (jessie)
Apache/2.4.10 (Debian)
Phusion_Passenger/6.0.2
ruby 2.4.6p354
</code>```

答:
You need to clear the session data to remove the existing OAuth token data. You can't use both token types simultaneously.

Per your comment (leaving an answer in case someone else has this same problem) you need to run:
RAILS_ENV=production rake db:sessions:clear

Body:
I'm trying to use omniauth-linkedin-oauth2 on RoR 5.0.7.

gem 'devise'
gem 'omniauth'
gem 'omniauth-oauth2'
gem 'omniauth-linkedin-oauth2'

but I got an error on production environment and I can not start rails apps. My local developing environment is no problem to run it.

The error on production.log is

NameError (uninitialized constant OAuth Did you mean?  OAuth2)

if I replaced

gem 'omniauth-linkedin-oauth2'

to

gem 'omniauth-linkedin'

and bundle update then there is no errors and RoR is running.

My production environment is

Debian GNU/Linux 8.11 (jessie)
Apache/2.4.10 (Debian)
Phusion_Passenger/6.0.2
ruby 2.4.6p354


问:
Conda-forge spaCy install fails - Error: WinError 87 - the parameter is incorrect
I'm trying to install spaCy in a conda environment (Anaconda 2019.03 - latest release) on Windows 10 using the command "conda install -c conda-forge spacy" recommended on the spaCy website. However I'm receiving OS Error 22 / WinError 87(the parameter is incorrect) when conda tries to install dependencies.

I've also tried installing spaCy using pip, but I run into similar difficulties. I get the same WinError 87 error - "the parameter is incorrect".

The full output from the conda attempt is:

```<code>(fever) C:\Users\Shmuli>conda install -v -c  conda-forge spacy

.....

===> LINKING PACKAGE: conda-forge::attrs-19.1.0-py_0 <===
  prefix=C:\Users\Shmuli\Anaconda3\envs\fever
  source=C:\Users\Shmuli\Anaconda3\pkgs\attrs-19.1.0-py_0

===> REVERSING PACKAGE LINK: conda-forge::attrs-19.1.0-py_0 <===
  prefix=C:\Users\Shmuli\Anaconda3\envs\fever

failed
An error occurred while installing package 'conda-forge::attrs-19.1.0-py_0'.
OSError(22, 'The parameter is incorrect', None, 87, None)
Attempting to roll back.

Rolling back transaction: ...working... ===> REVERSING PACKAGE LINK: conda-forge::asn1crypto-0.24.0-py37_1003 <===
  prefix=C:\Users\Shmuli\Anaconda3\envs\fever

===> REVERSING PACKAGE LINK: conda-forge::liblapack-3.8.0-10_mkl <===
  prefix=C:\Users\Shmuli\Anaconda3\envs\fever

===> REVERSING PACKAGE LINK: conda-forge::libcblas-3.8.0-10_mkl <===
  prefix=C:\Users\Shmuli\Anaconda3\envs\fever

===> REVERSING PACKAGE LINK: conda-forge::openssl-1.1.1b-hfa6e2cd_2 <===
  prefix=C:\Users\Shmuli\Anaconda3\envs\fever

===> REVERSING PACKAGE LINK: conda-forge::libblas-3.8.0-10_mkl <===
  prefix=C:\Users\Shmuli\Anaconda3\envs\fever

===> REVERSING PACKAGE LINK: defaults::mkl-2019.3-203 <===
  prefix=C:\Users\Shmuli\Anaconda3\envs\fever

rm_rf failed for C:\Users\Shmuli\Anaconda3\envs\fever\Library\bin\mkl_vml_avx2.dll

rm_rf failed for C:\Users\Shmuli\Anaconda3\envs\fever\Library\bin\mkl_rt.dll

rm_rf failed for C:\Users\Shmuli\Anaconda3\envs\fever\Library\bin\mkl_intel_thread.dll

rm_rf failed for C:\Users\Shmuli\Anaconda3\envs\fever\Library\bin\mkl_core.dll

rm_rf failed for C:\Users\Shmuli\Anaconda3\envs\fever\Library\bin\mkl_avx2.dll

===> REVERSING PACKAGE LINK: defaults::intel-openmp-2019.3-203 <===
  prefix=C:\Users\Shmuli\Anaconda3\envs\fever

rm_rf failed for C:\Users\Shmuli\Anaconda3\envs\fever\Library\bin\libiomp5md.dll

===> REVERSING PACKAGE LINK: conda-forge::ca-certificates-2019.3.9-hecc5488_0 <===
  prefix=C:\Users\Shmuli\Anaconda3\envs\fever

===> REVERSING PACKAGE UNLINK: defaults::ca-certificates-2019.1.23-0 <===
  prefix=C:\Users\Shmuli\Anaconda3\envs\fever

===> REVERSING PACKAGE UNLINK: defaults::openssl-1.1.1b-he774522_1 <===
  prefix=C:\Users\Shmuli\Anaconda3\envs\fever

===> REVERSING PACKAGE UNLINK: defaults::certifi-2019.3.9-py37_0 <===
  prefix=C:\Users\Shmuli\Anaconda3\envs\fever

done
Traceback (most recent call last):
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\core\link.py", line 622, in _execute_actions
    action.execute()
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\core\path_actions.py", line 558, in execute
    self.target_prefix, self.transaction_context['target_python_version'])
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\gateways\disk\create.py", line 380, in compile_multiple_pyc
    stdout, stderr, rc = any_subprocess(command, prefix)
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\gateways\subprocess.py", line 45, in any_subprocess
    stdout=PIPE, stderr=PIPE, env=env)
  File "C:\Users\Shmuli\Anaconda3\lib\subprocess.py", line 775, in __init__
    restore_signals, start_new_session)
  File "C:\Users\Shmuli\Anaconda3\lib\subprocess.py", line 1178, in _execute_child
    startupinfo)
OSError: [WinError 87] The parameter is incorrect

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\core\link.py", line 553, in _execute
    cls._execute_actions(pkg_idx_tracked, axngroup)
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\core\link.py", line 638, in _execute_actions
    reverse_excs,
conda.CondaMultiError: [WinError 87] The parameter is incorrect

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\exceptions.py", line 1003, in __call__
    return func(*args, **kwargs)
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\cli\main.py", line 84, in _main
    exit_code = do_call(args, p)
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\cli\conda_argparse.py", line 82, in do_call
    exit_code = getattr(module, func_name)(args, parser)
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\cli\main_install.py", line 20, in execute
    install(args, parser, 'install')
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\cli\install.py", line 275, in install
    handle_txn(unlink_link_transaction, prefix, args, newenv)
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\cli\install.py", line 304, in handle_txn
    unlink_link_transaction.execute()
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\core\link.py", line 241, in execute
    self._execute(tuple(concat(interleave(itervalues(self.prefix_action_groups)))))
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\core\link.py", line 587, in _execute
    rollback_excs,
conda.CondaMultiError: [WinError 87] The parameter is incorrect
</code>```

I tried just installing attrs using conda and received this error message:

```<code>Traceback (most recent call last):
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\core\link.py", line 622, in _execute_actions
    action.execute()
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\core\path_actions.py", line 558, in execute
    self.target_prefix, self.transaction_context['target_python_version'])
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\gateways\disk\create.py", line 380, in compile_multiple_pyc
    stdout, stderr, rc = any_subprocess(command, prefix)
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\gateways\subprocess.py", line 45, in any_subprocess
    stdout=PIPE, stderr=PIPE, env=env)
  File "C:\Users\Shmuli\Anaconda3\lib\subprocess.py", line 775, in __init__
    restore_signals, start_new_session)
  File "C:\Users\Shmuli\Anaconda3\lib\subprocess.py", line 1178, in _execute_child
    startupinfo)
OSError: [WinError 87] The parameter is incorrect

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\core\link.py", line 553, in _execute
    cls._execute_actions(pkg_idx_tracked, axngroup)
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\core\link.py", line 638, in _execute_actions
    reverse_excs,
conda.CondaMultiError: [WinError 87] The parameter is incorrect

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\exceptions.py", line 1003, in __call__
    return func(*args, **kwargs)
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\cli\main.py", line 84, in _main
    exit_code = do_call(args, p)
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\cli\conda_argparse.py", line 82, in do_call
    exit_code = getattr(module, func_name)(args, parser)
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\cli\main_install.py", line 20, in execute
    install(args, parser, 'install')
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\cli\install.py", line 275, in install
    handle_txn(unlink_link_transaction, prefix, args, newenv)
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\cli\install.py", line 304, in handle_txn
    unlink_link_transaction.execute()
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\core\link.py", line 241, in execute
    self._execute(tuple(concat(interleave(itervalues(self.prefix_action_groups)))))
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\core\link.py", line 587, in _execute
    rollback_excs,
conda.CondaMultiError: [WinError 87] The parameter is incorrect
</code>```

答: I'm not sure why exactly the WinError 87 was thrown, but I managed to solve the issue by shutting off auto containment in Comodo. Instructions for how to do so can be found here: https://steamcommunity.com/discussions/forum/1/617328967248066054/</p>

Body:
I'm trying to install spaCy in a conda environment (Anaconda 2019.03 - latest release) on Windows 10 using the command "conda install -c conda-forge spacy" recommended on the spaCy website. However I'm receiving OS Error 22 / WinError 87(the parameter is incorrect) when conda tries to install dependencies.

I've also tried installing spaCy using pip, but I run into similar difficulties. I get the same WinError 87 error - "the parameter is incorrect".

The full output from the conda attempt is:

(fever) C:\Users\Shmuli>conda install -v -c  conda-forge spacy

.....

===> LINKING PACKAGE: conda-forge::attrs-19.1.0-py_0 <===
  prefix=C:\Users\Shmuli\Anaconda3\envs\fever
  source=C:\Users\Shmuli\Anaconda3\pkgs\attrs-19.1.0-py_0

===> REVERSING PACKAGE LINK: conda-forge::attrs-19.1.0-py_0 <===
  prefix=C:\Users\Shmuli\Anaconda3\envs\fever

failed
An error occurred while installing package 'conda-forge::attrs-19.1.0-py_0'.
OSError(22, 'The parameter is incorrect', None, 87, None)
Attempting to roll back.

Rolling back transaction: ...working... ===> REVERSING PACKAGE LINK: conda-forge::asn1crypto-0.24.0-py37_1003 <===
  prefix=C:\Users\Shmuli\Anaconda3\envs\fever

===> REVERSING PACKAGE LINK: conda-forge::liblapack-3.8.0-10_mkl <===
  prefix=C:\Users\Shmuli\Anaconda3\envs\fever

===> REVERSING PACKAGE LINK: conda-forge::libcblas-3.8.0-10_mkl <===
  prefix=C:\Users\Shmuli\Anaconda3\envs\fever

===> REVERSING PACKAGE LINK: conda-forge::openssl-1.1.1b-hfa6e2cd_2 <===
  prefix=C:\Users\Shmuli\Anaconda3\envs\fever

===> REVERSING PACKAGE LINK: conda-forge::libblas-3.8.0-10_mkl <===
  prefix=C:\Users\Shmuli\Anaconda3\envs\fever

===> REVERSING PACKAGE LINK: defaults::mkl-2019.3-203 <===
  prefix=C:\Users\Shmuli\Anaconda3\envs\fever

rm_rf failed for C:\Users\Shmuli\Anaconda3\envs\fever\Library\bin\mkl_vml_avx2.dll

rm_rf failed for C:\Users\Shmuli\Anaconda3\envs\fever\Library\bin\mkl_rt.dll

rm_rf failed for C:\Users\Shmuli\Anaconda3\envs\fever\Library\bin\mkl_intel_thread.dll

rm_rf failed for C:\Users\Shmuli\Anaconda3\envs\fever\Library\bin\mkl_core.dll

rm_rf failed for C:\Users\Shmuli\Anaconda3\envs\fever\Library\bin\mkl_avx2.dll

===> REVERSING PACKAGE LINK: defaults::intel-openmp-2019.3-203 <===
  prefix=C:\Users\Shmuli\Anaconda3\envs\fever

rm_rf failed for C:\Users\Shmuli\Anaconda3\envs\fever\Library\bin\libiomp5md.dll

===> REVERSING PACKAGE LINK: conda-forge::ca-certificates-2019.3.9-hecc5488_0 <===
  prefix=C:\Users\Shmuli\Anaconda3\envs\fever

===> REVERSING PACKAGE UNLINK: defaults::ca-certificates-2019.1.23-0 <===
  prefix=C:\Users\Shmuli\Anaconda3\envs\fever

===> REVERSING PACKAGE UNLINK: defaults::openssl-1.1.1b-he774522_1 <===
  prefix=C:\Users\Shmuli\Anaconda3\envs\fever

===> REVERSING PACKAGE UNLINK: defaults::certifi-2019.3.9-py37_0 <===
  prefix=C:\Users\Shmuli\Anaconda3\envs\fever

done
Traceback (most recent call last):
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\core\link.py", line 622, in _execute_actions
    action.execute()
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\core\path_actions.py", line 558, in execute
    self.target_prefix, self.transaction_context['target_python_version'])
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\gateways\disk\create.py", line 380, in compile_multiple_pyc
    stdout, stderr, rc = any_subprocess(command, prefix)
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\gateways\subprocess.py", line 45, in any_subprocess
    stdout=PIPE, stderr=PIPE, env=env)
  File "C:\Users\Shmuli\Anaconda3\lib\subprocess.py", line 775, in __init__
    restore_signals, start_new_session)
  File "C:\Users\Shmuli\Anaconda3\lib\subprocess.py", line 1178, in _execute_child
    startupinfo)
OSError: [WinError 87] The parameter is incorrect

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\core\link.py", line 553, in _execute
    cls._execute_actions(pkg_idx_tracked, axngroup)
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\core\link.py", line 638, in _execute_actions
    reverse_excs,
conda.CondaMultiError: [WinError 87] The parameter is incorrect

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\exceptions.py", line 1003, in __call__
    return func(*args, **kwargs)
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\cli\main.py", line 84, in _main
    exit_code = do_call(args, p)
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\cli\conda_argparse.py", line 82, in do_call
    exit_code = getattr(module, func_name)(args, parser)
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\cli\main_install.py", line 20, in execute
    install(args, parser, 'install')
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\cli\install.py", line 275, in install
    handle_txn(unlink_link_transaction, prefix, args, newenv)
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\cli\install.py", line 304, in handle_txn
    unlink_link_transaction.execute()
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\core\link.py", line 241, in execute
    self._execute(tuple(concat(interleave(itervalues(self.prefix_action_groups)))))
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\core\link.py", line 587, in _execute
    rollback_excs,
conda.CondaMultiError: [WinError 87] The parameter is incorrect

I tried just installing attrs using conda and received this error message:

Traceback (most recent call last):
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\core\link.py", line 622, in _execute_actions
    action.execute()
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\core\path_actions.py", line 558, in execute
    self.target_prefix, self.transaction_context['target_python_version'])
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\gateways\disk\create.py", line 380, in compile_multiple_pyc
    stdout, stderr, rc = any_subprocess(command, prefix)
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\gateways\subprocess.py", line 45, in any_subprocess
    stdout=PIPE, stderr=PIPE, env=env)
  File "C:\Users\Shmuli\Anaconda3\lib\subprocess.py", line 775, in __init__
    restore_signals, start_new_session)
  File "C:\Users\Shmuli\Anaconda3\lib\subprocess.py", line 1178, in _execute_child
    startupinfo)
OSError: [WinError 87] The parameter is incorrect

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\core\link.py", line 553, in _execute
    cls._execute_actions(pkg_idx_tracked, axngroup)
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\core\link.py", line 638, in _execute_actions
    reverse_excs,
conda.CondaMultiError: [WinError 87] The parameter is incorrect

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\exceptions.py", line 1003, in __call__
    return func(*args, **kwargs)
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\cli\main.py", line 84, in _main
    exit_code = do_call(args, p)
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\cli\conda_argparse.py", line 82, in do_call
    exit_code = getattr(module, func_name)(args, parser)
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\cli\main_install.py", line 20, in execute
    install(args, parser, 'install')
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\cli\install.py", line 275, in install
    handle_txn(unlink_link_transaction, prefix, args, newenv)
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\cli\install.py", line 304, in handle_txn
    unlink_link_transaction.execute()
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\core\link.py", line 241, in execute
    self._execute(tuple(concat(interleave(itervalues(self.prefix_action_groups)))))
  File "C:\Users\Shmuli\Anaconda3\lib\site-packages\conda\core\link.py", line 587, in _execute
    rollback_excs,
conda.CondaMultiError: [WinError 87] The parameter is incorrect


问:
Why does Java allow only a single method X when implementing 2 interfaces that both declare X but which differ in their throws clauses?
This is closely related to, but is not the same question as: Java - Method name collision in interface implementation

When there are two Java interfaces that share a method with almost the same signature like so:

```<code>import java.io.IOException;

interface ISomething1 {
    void doSomething();
}

interface ISomething2 {
    void doSomething() throws IOException;
}

class Impl implements ISomething1, ISomething2 {
  public void doSomething() {
    throw new IOException(); // this does not compile since ISomething1.doSomething does not declare a throws clause
  }

  public static void main(String args[]) throws IOException {
    Impl i = new Impl();
    i.doSomething();
  }
}
</code>```

Why is it that Java enforces that only a single method implement both these interface methods even though technically they differ in signature?

Note also that in the example above, the implementation of Impl.doSomething needs to NOT throw an IOException as otherwise the compiler complains that ISomething1.doSomething must also declare that it throws IOException effectively making the throws clause in ISomething2.doSomething useless.

Am I missing something obvious here? Thanks in advance for responses.

答:
You might expect the compiler to know whether your client code intends to call void doSomething(); or void doSomething() throws IOException; based upon whether that client code handles the exception.

But the Java compiler is just not that clever.

(Of course, it would be impossible to infer which method the client wanted to call if the thrown exception was a RuntimeException - no matter how clever the compiler was).

The only things that make up the type of a method signature are the name and the parameters.

Body:
This is closely related to, but is not the same question as: Java - Method name collision in interface implementation

When there are two Java interfaces that share a method with almost the same signature like so:

import java.io.IOException;

interface ISomething1 {
    void doSomething();
}

interface ISomething2 {
    void doSomething() throws IOException;
}

class Impl implements ISomething1, ISomething2 {
  public void doSomething() {
    throw new IOException(); // this does not compile since ISomething1.doSomething does not declare a throws clause
  }

  public static void main(String args[]) throws IOException {
    Impl i = new Impl();
    i.doSomething();
  }
}

Why is it that Java enforces that only a single method implement both these interface methods even though technically they differ in signature?

Note also that in the example above, the implementation of Impl.doSomething needs to NOT throw an IOException as otherwise the compiler complains that ISomething1.doSomething must also declare that it throws IOException effectively making the throws clause in ISomething2.doSomething useless.

Am I missing something obvious here? Thanks in advance for responses.


问:
How to use an android dependency in unit tests?
I'm currently trying out TDD, but cannot get my head around how to use android dependencys in my unit tests.

I want to parse the JSON response of the PONS API to an Object.
To test my Jsonparser, I tried to create a mock a spy, or just to a normal instance of the JsonReader the android.utils.JsonReader, which i then pass to my parser.

```<code>
@Mock
private var reader : JsonReader = JsonReader(BufferedReader(FileReader(fileName)))

@Before
fun setUp(){
    MockitoAnnotations.initMocks(this)
}

@Test
fun parseTest() {

    val response = ResponseParser.parse(reader)

    val entry : response.Entry = response.getEntry(0)

    assertThat(entry.strings_displayed[0].get(0).first, `is`("Haus (Wohnhaus, Heim)"))
    assertThat(entry.strings_displayed[0].get(0).second, `is`("casa"))
    }

</code>```

however none of my attempts has yielded the desired output. As of now i'm not able to use the JsonReader class. All i get is this error message (which of cause has been googled)

```<code>java.lang.RuntimeException: Method beginObject in android.util.JsonReader not mocked. See http://g.co/androidstudio/not-mocked for details.
at android.util.JsonReader.beginObject(JsonReader.java)
at com.huckebrink.remindyct.Data.PONSRequestParser$Companion.readJsonString(PONSRequestParser.kt:23)
at com.huckebrink.remindyct.Data.PONSRequestParser$Companion.parse(PONSRequestParser.kt:13)
at com.huckebrink.remindyct.ParsingUnitTest.parseTest(ParsingUnitTest.kt:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
</code>```

答:
Well, my recommendation is to try to keep your Unit Test level without depending on the Android Framework, it makes everything easy if you can test only with Kotlin pure at Unit level and leave more complex tests for the Integration level.

Sometimes it's not so easy if the app is coupled, so, you can use some library as Robolectric to have the Android Framework working partially in your Unit Tests.

Search for: "Robolectric unit tests" to get examples. Good luck

UPDATE:

From the Android documentation https://developer.android.com/training/testing/unit-testing

Local tests: Unit tests that run on your local machine only. These tests are compiled to run locally on the Java Virtual Machine (JVM) to minimize execution time. If your tests depend on objects in the Android framework, we recommend using Robolectric. For tests that depend on your own dependencies, use mock objects to emulate your dependencies' behavior.

UPDATE 2:

JSON parsing should be part of the instrumented/integration level of tests, anyway, if you want the dependencies to use JsonParing on test directory you can add:

testCompile ‘org.json:json:20140107’

Body:
I'm currently trying out TDD, but cannot get my head around how to use android dependencys in my unit tests.

I want to parse the JSON response of the PONS API to an Object.
To test my Jsonparser, I tried to create a mock a spy, or just to a normal instance of the JsonReader the android.utils.JsonReader, which i then pass to my parser.

@Mock
private var reader : JsonReader = JsonReader(BufferedReader(FileReader(fileName)))

@Before
fun setUp(){
    MockitoAnnotations.initMocks(this)
}

@Test
fun parseTest() {

    val response = ResponseParser.parse(reader)

    val entry : response.Entry = response.getEntry(0)

    assertThat(entry.strings_displayed[0].get(0).first, `is`("Haus (Wohnhaus, Heim)"))
    assertThat(entry.strings_displayed[0].get(0).second, `is`("casa"))
    }

however none of my attempts has yielded the desired output. As of now i'm not able to use the JsonReader class. All i get is this error message (which of cause has been googled)

java.lang.RuntimeException: Method beginObject in android.util.JsonReader not mocked. See http://g.co/androidstudio/not-mocked for details.
at android.util.JsonReader.beginObject(JsonReader.java)
at com.huckebrink.remindyct.Data.PONSRequestParser$Companion.readJsonString(PONSRequestParser.kt:23)
at com.huckebrink.remindyct.Data.PONSRequestParser$Companion.parse(PONSRequestParser.kt:13)
at com.huckebrink.remindyct.ParsingUnitTest.parseTest(ParsingUnitTest.kt:47)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)


问:
Can we modify or customise the data structure(for e.g. tree, Linked List etc.) of Java object(s)?
I recently came across header nodes concept in tree & linked-list data structures & while practising the same in Java I felt if it's possible to have my reference variable as a header node by default for the object I'm creating via 'new' keyword.

As we know currently when we create any object by means such as 'new' keyword, factory methods, cloning etc. we basically make the reference variable as Root node & the instance variable(s) are akin to child nodes[which if are objects would of course increase the length of linked-list(in case of single instance variable) or level of tree(in case of multiple instance variables)].

Since header nodes provide advantages like no need of null checks, I feel it would be great to integrate it with my application development. However I'm unable to figure out how to override the existing behaviour of JVM/JRE which creates the objects.

Thanks in advance!

答:
Can you clarify your question? Are you asking how to override the way Java creates objects? If so, you can't override it. When initializing a Linked List, the first node that is pushed to the linked list becomes the head node. The next node that is pushed becomes linked to the head node. Then, each node that is pushed to the linked list becomes linked to the previous node. </p>

<p>When creating a custom linked list, you could implement a function that pushes the elements in ascending order, so that the list is sorted. So, that's one way you could change the way a Linked list is created. However, you can't override the process of using the 'new' keyword, factory methods, or cloning to actually create the object. </p>

Body:
Can you clarify your question? Are you asking how to override the way Java creates objects? If so, you can't override it. When initializing a Linked List, the first node that is pushed to the linked list becomes the head node. The next node that is pushed becomes linked to the head node. Then, each node that is pushed to the linked list becomes linked to the previous node.

When creating a custom linked list, you could implement a function that pushes the elements in ascending order, so that the list is sorted. So, that's one way you could change the way a Linked list is created. However, you can't override the process of using the 'new' keyword, factory methods, or cloning to actually create the object.


问:
send user data from login page to main activity and logout from main activity as well
I created two activites one LoginActivity and other MainActivity where I want to get user data to be shown like name and photos, then I want user to log out from MainActivity as well. I made a google sign in button from a tutorial where login, logout and userdata was shown in same activity.
Now I know I have to put explicit intent on (if login is successful) but I don't know how do I carry userdata like emailID, name(at least), photo to next activity where I use them and update using updateUI method which updated the user details previously in the same Login activity.

My login activity

public class LoginActivity extends AppCompatActivity {

```<code>static final int GOOGLE_SIGN_IN = 123;
FirebaseAuth mAuth;
Button btn_login, btn_logout;
TextView text;
ImageView image;
ProgressBar progressBar;
GoogleSignInClient mGoogleSignInClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    btn_login = findViewById(R.id.login);
    btn_logout = findViewById(R.id.logout);
    text = findViewById(R.id.text);
    image = findViewById(R.id.image);
    progressBar = findViewById(R.id.progress_circular);

    mAuth = FirebaseAuth.getInstance();

    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();

    mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

    btn_login.setOnClickListener(v -> SignInGoogle());
    btn_logout.setOnClickListener(v -> Logout());

    if (mAuth.getCurrentUser() != null) {
        FirebaseUser user = mAuth.getCurrentUser();
        updateUI(user);
    }
}

public void SignInGoogle() {
    progressBar.setVisibility(View.VISIBLE);
    Intent signInIntent = mGoogleSignInClient.getSignInIntent();
    startActivityForResult(signInIntent, GOOGLE_SIGN_IN);
}

private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d("TAG", "firebaseAuthWithGoogle:" + acct.getId());

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, task -> {
                if (task.isSuccessful()) {
                    progressBar.setVisibility(View.INVISIBLE);

                    Log.d("TAG", "signInWithCredential:success");

                    FirebaseUser user = mAuth.getCurrentUser();
                    updateUI(user);
                } else {
                    progressBar.setVisibility(View.INVISIBLE);

                    Log.w("TAG", "signInWithCredential:failure", task.getException());

                    Toast.makeText(LoginActivity.this, "Authentication failed.",
                            Toast.LENGTH_SHORT).show();
                    updateUI(null);
                }
            });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == GOOGLE_SIGN_IN) {
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        try {
            GoogleSignInAccount account = task.getResult(ApiException.class);
            if (account != null) firebaseAuthWithGoogle(account);
        } catch (ApiException e) {
            Log.w("TAG", "Google sign in failed", e);
        }
    }
}

private void updateUI(FirebaseUser user) {
    if (user != null)
    {
        String name = user.getDisplayName();
        String email = user.getEmail();
        String photo = String.valueOf(user.getPhotoUrl());
        for (UserInfo userInfo : user.getProviderData())
            if (name == null && userInfo.getDisplayName() != null)
                name = userInfo.getDisplayName();
        text.append("Info : \n");
        text.append(name + "\n");
        text.append(email);
        Picasso.get().load(photo).into(image);
        btn_logout.setVisibility(View.VISIBLE);
        btn_login.setVisibility(View.INVISIBLE);
    } else
    {
        text.setText("Distress Alert\n");
        btn_logout.setVisibility(View.INVISIBLE);
        btn_login.setVisibility(View.VISIBLE);
        Picasso.get().load(R.drawable.ic_firebase_logo).into(image);

    }
}

private void Logout()
{
    FirebaseAuth.getInstance().signOut();
    mGoogleSignInClient.signOut().addOnCompleteListener(this,
            task -> updateUI(null));
}
</code>```

}

答:
I do not have commenting privileges as of yet, but a simple google search for passing data between activities would have given you this.

How do I pass data between Activities in Android application?

Also, using Intent in this case would not be a good solution, as you're already using Firebase for authentication, you can get the current FirebaseUser in next Activity.

Declare an instance (class variable)

```<code>private FirebaseAuth mAuth;
</code>```

In onCreate() initialize mAuth

```<code>mAuth = FirebaseAuth.getInstance();
</code>```

In onStart() check if the user is signed in and check for null

```<code>@Override
public void onStart() {
    super.onStart();
    FirebaseUser currentUser = mAuth.getCurrentUser();
    if (currentUser == null) {
        // No user is signed in
    } else {
        // User logged in
    }
}
</code>```

Using the second method you can get the complete FirebaseUser object in next activity if the user is signed in. Or, you can use Intent to pass data between activities.

Body:
I created two activites one LoginActivity and other MainActivity where I want to get user data to be shown like name and photos, then I want user to log out from MainActivity as well. I made a google sign in button from a tutorial where login, logout and userdata was shown in same activity.
Now I know I have to put explicit intent on (if login is successful) but I don't know how do I carry userdata like emailID, name(at least), photo to next activity where I use them and update using updateUI method which updated the user details previously in the same Login activity.

My login activity

public class LoginActivity extends AppCompatActivity {

static final int GOOGLE_SIGN_IN = 123;
FirebaseAuth mAuth;
Button btn_login, btn_logout;
TextView text;
ImageView image;
ProgressBar progressBar;
GoogleSignInClient mGoogleSignInClient;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    btn_login = findViewById(R.id.login);
    btn_logout = findViewById(R.id.logout);
    text = findViewById(R.id.text);
    image = findViewById(R.id.image);
    progressBar = findViewById(R.id.progress_circular);

    mAuth = FirebaseAuth.getInstance();

    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();

    mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

    btn_login.setOnClickListener(v -> SignInGoogle());
    btn_logout.setOnClickListener(v -> Logout());

    if (mAuth.getCurrentUser() != null) {
        FirebaseUser user = mAuth.getCurrentUser();
        updateUI(user);
    }
}

public void SignInGoogle() {
    progressBar.setVisibility(View.VISIBLE);
    Intent signInIntent = mGoogleSignInClient.getSignInIntent();
    startActivityForResult(signInIntent, GOOGLE_SIGN_IN);
}

private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d("TAG", "firebaseAuthWithGoogle:" + acct.getId());

    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, task -> {
                if (task.isSuccessful()) {
                    progressBar.setVisibility(View.INVISIBLE);

                    Log.d("TAG", "signInWithCredential:success");

                    FirebaseUser user = mAuth.getCurrentUser();
                    updateUI(user);
                } else {
                    progressBar.setVisibility(View.INVISIBLE);

                    Log.w("TAG", "signInWithCredential:failure", task.getException());

                    Toast.makeText(LoginActivity.this, "Authentication failed.",
                            Toast.LENGTH_SHORT).show();
                    updateUI(null);
                }
            });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == GOOGLE_SIGN_IN) {
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        try {
            GoogleSignInAccount account = task.getResult(ApiException.class);
            if (account != null) firebaseAuthWithGoogle(account);
        } catch (ApiException e) {
            Log.w("TAG", "Google sign in failed", e);
        }
    }
}

private void updateUI(FirebaseUser user) {
    if (user != null)
    {
        String name = user.getDisplayName();
        String email = user.getEmail();
        String photo = String.valueOf(user.getPhotoUrl());
        for (UserInfo userInfo : user.getProviderData())
            if (name == null && userInfo.getDisplayName() != null)
                name = userInfo.getDisplayName();
        text.append("Info : \n");
        text.append(name + "\n");
        text.append(email);
        Picasso.get().load(photo).into(image);
        btn_logout.setVisibility(View.VISIBLE);
        btn_login.setVisibility(View.INVISIBLE);
    } else
    {
        text.setText("Distress Alert\n");
        btn_logout.setVisibility(View.INVISIBLE);
        btn_login.setVisibility(View.VISIBLE);
        Picasso.get().load(R.drawable.ic_firebase_logo).into(image);

    }
}

private void Logout()
{
    FirebaseAuth.getInstance().signOut();
    mGoogleSignInClient.signOut().addOnCompleteListener(this,
            task -> updateUI(null));
}

}

Body:
I do not have commenting privileges as of yet, but a simple google search for passing data between activities would have given you this.

How do I pass data between Activities in Android application?

Also, using Intent in this case would not be a good solution, as you're already using Firebase for authentication, you can get the current FirebaseUser in next Activity.

Declare an instance (class variable)

private FirebaseAuth mAuth;

In onCreate() initialize mAuth

mAuth = FirebaseAuth.getInstance();

In onStart() check if the user is signed in and check for null

@Override
public void onStart() {
    super.onStart();
    FirebaseUser currentUser = mAuth.getCurrentUser();
    if (currentUser == null) {
        // No user is signed in
    } else {
        // User logged in
    }
}

Using the second method you can get the complete FirebaseUser object in next activity if the user is signed in. Or, you can use Intent to pass data between activities.


问:
I have a problem in a div element position
Im trying to position the div element in the center responsively but the top-left corner act as I want (it goes to center instead of the whole div) what should I do?</p>

```<code><!DOCTYPE html>
<html lang="en" dir="ltr">
  <body>
  <div class="container"></div>
  <input class="click-button" type="button" name="button" value="Click" onclick="clearWrite()"></button>
  <p id="text"></p>
    <script type="text/javascript" src="js/javascript.js"></script>
  </body>
</html>
</code>```

```<code>body {
  background-color: rgba(75, 75, 75, 0.7); }

.container {
  background-color: white;
  height: 360px;
  width: 640px;
  position: absolute;
  top: 50%;
  left: 50%;
}
</code>```

答:
Using translate(-50%,-50%) it would shift in Y and X axis to 50%  of its height and width.

body {
  background-color: rgba(75, 75, 75, 0.7);
}

.container {
  background-color: white;
  height: 200px;
  width: 200px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /** add this **/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<body>
  <div class="container"></div>
  <input class="click-button" type="button" name="button" value="Click" onclick="clearWrite()">
  <p id="text"></p>
  <script type="text/javascript" src="js/javascript.js"></script>
  </body>
  </html></code>```

Body:
Im trying to position the div element in the center responsively but the top-left corner act as I want (it goes to center instead of the whole div) what should I do?

<!DOCTYPE html>

  <input class="click-button" type="button" name="button" value="Click" onclick="clearWrite()"></button>

body {
  background-color: rgba(75, 75, 75, 0.7); }

.container {
  background-color: white;
  height: 360px;
  width: 640px;
  position: absolute;
  top: 50%;
  left: 50%;
}

Body:
Using translate(-50%,-50%) it would shift in Y and X axis to 50%  of its height and width.

body {
  background-color: rgba(75, 75, 75, 0.7);
}

.container {
  background-color: white;
  height: 200px;
  width: 200px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /** add this **/
}

<!DOCTYPE html>
<html>
<body>
  <div class="container"></div>
  <input class="click-button" type="button" name="button" value="Click" onclick="clearWrite()">
  <p id="text"></p>
  <script type="text/javascript" src="js/javascript.js"></script>
  </body>
  </html>


问:
How do I create an Outlook calendar subscription from my web/app server?
I have a website that is a calendar with all the basic features (ASP.NET MVC and SQL Server). People can enter events, view others events, etc. One person asked me if there was a way they can see these events in their Outlook calendar - as a second calendar.

I have all of the data on the server. Is there a recommended way to have Outlook point to my web server or DB for a calendar? I see there are ways to generate iCal files from C#.

If so, how would this data stay in sync as new events are created, deleted, etc? A one time dump would be ok but the concern would be that the data would get stale. Is there a solution that would keep the reference dynamic to keep them in sync.  (it would only need to be a one way transfer, i don't expect the need to create or delete from Outlook, so outlook is just read only)

答:
You could try to keep track of the SEQUENCE of updates to each calendar entry in your database, and add a trigger on your table of calendar events so that it would automatically send event updates when something changes. Each update would have a higher SEQUENCE property than the updates that came before it, but the UID (the event's unique identifier) would remain the same.

For this to work, though, you'd need to be able to send iCalendar events from within your SQL Server, which can be possible using the following CLR project:

github.com/EitanBlumin/sql-clr-ics


问:
PHP Laravel how to use two forms in one view
I'm building a Laravel-app where I have two forms in one blade-template, which appears depending on which tab is active.

It looks like this:

```<code><div data-contact-form-id="1" class="contact-form" id="contact-company">
    <form method="POST" action="{{ route('contact.company') }}">
    // bunch of input fields here
   </form>
</div>
<div data-contact-form-id="2" class="contact-form" id="contact-private">
    <form method="POST" action="{{ route('contact.store') }}">
    // bunch of input fields here
   </form>
</div>
</code>```

then my web.php

```<code>Route::post('contact', 'ContactController@store')->name('contact.store');
Route::post('contact/company', 'ContactController@company')->name('contact.company');
</code>```

but I can't submit the "company-contact" form, and when I try to do remove the slash in the route I get an error route.store is not defined:

```<code>Route::post('contact', 'ContactController@store')->name('contact.store');
Route::post('contact', 'ContactController@company')->name('contact.company');
</code>```

Why is this and how can I solve this?

答:
put all input fields in a single form and submit to the store route.

In controller:

Here I used the company model & some fields just for example you can replace with your model & your field name

```<code>public function store(Request $request){
  $post = $request->all();

  Company::create([
      'company_name' => $post['company_name']
      'company_email' => $post['company_email'],
      'company_phone' => $post['company_phone']
  ]);

   // another model for contact
   Contact::create([
     'name' => $post['name'],
     'email' => $post['email'],
     'phone' => $post['phone'],
   ]);
}
</code>```

Body:
I'm building a Laravel-app where I have two forms in one blade-template, which appears depending on which tab is active.

It looks like this:

    <form method="POST" action="{{ route('contact.company') }}">
    // bunch of input fields here
   </form>

    <form method="POST" action="{{ route('contact.store') }}">
    // bunch of input fields here
   </form>

then my web.php

Route::post('contact', 'ContactController@store')->name('contact.store');
Route::post('contact/company', 'ContactController@company')->name('contact.company');

but I can't submit the "company-contact" form, and when I try to do remove the slash in the route I get an error route.store is not defined:

Route::post('contact', 'ContactController@store')->name('contact.store');
Route::post('contact', 'ContactController@company')->name('contact.company');

Why is this and how can I solve this?

Body:
put all input fields in a single form and submit to the store route.

In controller:

Here I used the company model & some fields just for example you can replace with your model & your field name

public function store(Request $request){
  $post = $request->all();

  Company::create([
      'company_name' => $post['company_name']
      'company_email' => $post['company_email'],
      'company_phone' => $post['company_phone']
  ]);

   // another model for contact
   Contact::create([
     'name' => $post['name'],
     'email' => $post['email'],
     'phone' => $post['phone'],
   ]);
}


问:
How do you get the asp:Menu to follow the url provided in the Web.sitemap?
I have a simple asp:menu-item that uses the Web.sitemap to get the menu items. The page will postback but fails to get the page associated to the clicked item. I will mention that the navigation bar code is within the masterpage file.

```<code><div>
  <asp:SiteMapDataSource ID="SiteMapDataSource1"  ShowStartingNode="false" runat="server" />
  <asp:Menu ID="Menu1" Orientation="horizontal"  runat="server" BackColor="#a0a080" DataSourceID="SiteMapDataSource1"
      DynamicHorizontalOffset="2" Font-Names="Verdana" Font-Size="0.8em" ForeColor="#a00000"
      StaticSubMenuIndent="10px" Style="z-index: 2; left: 390px; position: absolute;
      top: 281px" Height="20px" Width="311px">
      <StaticSelectedStyle BackColor="#a0a080" />
      <StaticMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" />
      <DynamicHoverStyle BackColor="#a0a080" ForeColor="White" />
      <DynamicMenuStyle BackColor="#a0a080" />
      <DynamicSelectedStyle BackColor="#a0a080" />
      <DynamicMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" />
      <DataBindings>
          <asp:MenuItemBinding DataMember="SiteMapNode" EnabledField="Title" TextField="Title" />
      </DataBindings>
      <StaticHoverStyle BackColor="#666666" ForeColor="White" />
  </asp:Menu>
</div>

<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
  <siteMapNode url="" title=""  description="">
    <siteMapNode title="Home"  description="Zombie (be)Warehouse" url="index.aspx" />
    <siteMapNode title="Armor" description="Anti-Zombie Armor" url="Armor.aspx" />
    <siteMapNode title="Weapons" description="Anti-Zombie Weapons" url="Weapons.aspx" />
    <siteMapNode title="Manuals" description="Survival Manuals" url="Manuals.aspx" />
    <siteMapNode title="Sustenance" description="Prepared food for survival" url="Sustenance.aspx" />
    <siteMapNode title="Contacts"  description="Contact Us"  url="Contacts.aspx" />
    <siteMapNode title="About" description="About Zombie (be)Warehouse" url="About.aspx" />
  </siteMapNode>
</siteMap>
</code>```

Update:
The problem is being found in the DataBindings section of the menu item. Notice the line:

```<code><asp:MenuItemBinding DataMember="SiteMapNode" EnabledField="Title" Text="Title" />
</code>```

The Text="Title" sets the menu's displayed text from the Web.sitemap's text field. I noticed that the MenuItemBinding item had a field called NavigateUrlField.

So to solve this issue, you simple need to change/add to the asp:MenuItemBinding

```<code><asp:MenuItemBinding DataMember="SiteMapNode" NavigateUrlField="url" EnabledField="Title" TextField="Title" />
</code>```

答: You need to add the NavigateUrlField field to the MenuItemBinding like this   <asp:MenuItemBinding DataMember="SiteMapNode" EnabledField="Title" TextField="Title" NavigateUrlField="url"/>

OwnerDisplayName: Matt R

Body:
I have a simple asp:menu-item that uses the Web.sitemap to get the menu items. The page will postback but fails to get the page associated to the clicked item. I will mention that the navigation bar code is within the masterpage file.

  <asp:SiteMapDataSource ID="SiteMapDataSource1"  ShowStartingNode="false" runat="server" />
  <asp:Menu ID="Menu1" Orientation="horizontal"  runat="server" BackColor="#a0a080" DataSourceID="SiteMapDataSource1"
      DynamicHorizontalOffset="2" Font-Names="Verdana" Font-Size="0.8em" ForeColor="#a00000"
      StaticSubMenuIndent="10px" Style="z-index: 2; left: 390px; position: absolute;
      top: 281px" Height="20px" Width="311px">
      <StaticSelectedStyle BackColor="#a0a080" />
      <StaticMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" />
      <DynamicHoverStyle BackColor="#a0a080" ForeColor="White" />
      <DynamicMenuStyle BackColor="#a0a080" />
      <DynamicSelectedStyle BackColor="#a0a080" />
      <DynamicMenuItemStyle HorizontalPadding="5px" VerticalPadding="2px" />
      <DataBindings>
          <asp:MenuItemBinding DataMember="SiteMapNode" EnabledField="Title" TextField="Title" />
      </DataBindings>
      <StaticHoverStyle BackColor="#666666" ForeColor="White" />
  </asp:Menu>

<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
  <siteMapNode url="" title=""  description="">
    <siteMapNode title="Home"  description="Zombie (be)Warehouse" url="index.aspx" />
    <siteMapNode title="Armor" description="Anti-Zombie Armor" url="Armor.aspx" />
    <siteMapNode title="Weapons" description="Anti-Zombie Weapons" url="Weapons.aspx" />
    <siteMapNode title="Manuals" description="Survival Manuals" url="Manuals.aspx" />
    <siteMapNode title="Sustenance" description="Prepared food for survival" url="Sustenance.aspx" />
    <siteMapNode title="Contacts"  description="Contact Us"  url="Contacts.aspx" />
    <siteMapNode title="About" description="About Zombie (be)Warehouse" url="About.aspx" />
  </siteMapNode>
</siteMap>

Update:
The problem is being found in the DataBindings section of the menu item. Notice the line:

<asp:MenuItemBinding DataMember="SiteMapNode" EnabledField="Title" Text="Title" />

The Text="Title" sets the menu's displayed text from the Web.sitemap's text field. I noticed that the MenuItemBinding item had a field called NavigateUrlField.

So to solve this issue, you simple need to change/add to the asp:MenuItemBinding

<asp:MenuItemBinding DataMember="SiteMapNode" NavigateUrlField="url" EnabledField="Title" TextField="Title" />

LastEditorDisplayName: Matt R


答:
I would do this as:

```<code>select id, sumval - maxval
from t cross apply
     (select sum(val) as sumval, max(val) as maxval
      from values (value1), (value2), (value3)) v(val)
     ) v;
</code>```

If you have three items, the sum of the smallest two is the sum of all of them minus the largest.

More generally, I would use something like this:

```<code>select id, sum2
from t cross apply
     (select sum(val) as sum2
      from (select top (2) val
            from values (value1), (value2), (value3) v(val)
            order by val asc
           ) v
     ) v
</code>```

Title: Sum the two lowest values from a record

Body:
I have a table like this:

I need to sum the two lowest values for each record. For example, in the first row 2 and 4 (2 + 4 = 6).

I can find the lowest value for each row using CROSS APPLY, but I can't find the two lowest values at once to sum them.

Thanks in advance.

Body:
I would do this as:

select id, sumval - maxval
from t cross apply
     (select sum(val) as sumval, max(val) as maxval
      from values (value1), (value2), (value3)) v(val)
     ) v;

If you have three items, the sum of the smallest two is the sum of all of them minus the largest.

More generally, I would use something like this:

select id, sum2
from t cross apply
     (select sum(val) as sum2
      from (select top (2) val
            from values (value1), (value2), (value3) v(val)
            order by val asc
           ) v
     ) v


问:
Staticlink vs standalone quirk with F#
In vs2010 ultimate edition if you hand the --standalone flag to the f# compiler in the projects pane it will not link an empty C# project with a configuration files/resource files

It will, however, link the assembly if you explicitly declare --staticlink:Config

This feels like a bug...if it is intentional, may I ask why this would be?

答:
This is an expected behavior:

The standalone flag statically links the FSharp.Core.dll (F# runtime) and any reference assemblies that depend on it (i.e. any other F# assemblies). They need to be linked because they may share some types with the primary assembly (e.g. F# list type etc.)

The staticlink flag links any assembly that you explicitly specify (and any assemblies that depend on it). This means that you can use the option to link, for example, C# library that your main F# assembly references.

I think that the two cases are handled separately, because inlining F# runtime requires slightly special handling (almost all F# code uses it in some way, and the compiler probably  treats it differently)

Title: Staticlink vs standalone quirk with F#


问:
jS code is not working, not showing total
I am trying to calculate three values using JS, but the total is not being calculated. it gets values from the form elements and then function calculateTotal() is called onchange. But the total is not being displayed.
*I am new on stackoverflow, please be kind!

I was trying to use method Post on the form, removed it.
Also removed any styling.

function getpkgPriceA() {
  //Get a reference to the form id="Mangoform"
  var theForm = document.forms["Mangoform"];
  //Get a reference to the select id="qtyA"
  var QuantityA = theForm.elements["qtyA"];
  if (QuantityA == null || QuantityA === false) {
    var totalpkgPriceA = 0;
    return totalpkgPriceA;
  } else {
    var totalpkgPriceA = 5.99 * QuantityA.value;
    return totalpkgPriceA;
  }
}

function getpkgPriceB() {
  //Get a reference to the form id="Mangoform"
  var theForm = document.forms["Mangoform"];
  //Get a reference to the select id="qtyB"
  var QuantityB = theForm.elements["qtyB"];
  if (QuantityB == null || QuantityB === false) {
    var totalpkgPriceB = 0;
    return totalpkgPriceB;
  } else {
    var totalpkgPriceB = 12.99 * QuantityB.value;
    return totalpkgPriceB;
  }
}

function getpkgPriceC() {
  //Get a reference to the form id="Mangoform"
  var theForm = document.forms["Mangoform"];
  //Get a reference to the select id="qtyC"
  var QuantityC = theForm.elements["qtyC"];
  if (QuantityC == null || QuantityC === false) {
    var totalpkgPriceC = 0;
    return totapkgPriceC;
  } else {
    var totalpkgPriceC = 17.99 * QuantityC.value;
    return totalpkgPriceC;
  }
}

function calculateTotal() {

  var TotalpkgPrice = getpkgPriceA() + getpkgPriceB() + getpkgPriceC() + 2;
  //display the result
  var divobj = document.getElementById('totalprice');
  divobj.style.display = 'block';
  divobj.innerHTML = "Your Total: £"
  TotalpkgPrice.toFixed(2);
}

function hideTotal() {
  var divobj = document.getElementById('totalprice');
  divobj.style.display = 'none';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form action="#" id="Mangoform">
  <div>
    <div>
      <div>
        <span>Small: 1.3kg</span>
        <input type="number" id="qtyA" name="qtyA" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100">
      </div>
      </br>
      <div>
        <span>Large: 3.3kg</span>
        <input type="number" id="qtyB" name="qtyB" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100">
      </div>
      </br>
      <div>
        <span>Small: 5.0kg</span>
        <input type="number" id="qtyC" name="qtyC" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100">
      </div>
    </div>
  </div>
  <span id="totalprice" name='totalprice'>Your Total:</span>
  <div>
    <input name="submit" type="submit" value="submit" onclick="calculateTotal()">
  </div>
</form></code>```

if value in qtyA=1, qtyB=1 and qtyC=1 and adding 2 then total should be displayed

as 38.97

(5.99*1)+(12.99*1)+(17.99*1)+2=38.97

if qtyA=2, qtyB=2 and qtyC=3 adding 2
(5.99*2)+(12.99*2)+(17.99*3)+2=93.93

Please point out the mistake. Thanks.

答:
function getpkgPriceA() {

  //Get a reference to the form id="Mangoform"
  var theForm = document.forms["Mangoform"];
  //Get a reference to the select id="qtyA"

  var QuantityA = theForm.elements["qtyA"];
  if (QuantityA == null || QuantityA === false) {
    var totalpkgPriceA = 0;
    return totalpkgPriceA;
  } else {
    var totalpkgPriceA = 5.99 * QuantityA.value;
    return totalpkgPriceA;
  }
}

function getpkgPriceB() {

  //Get a reference to the form id="Mangoform"
  var theForm = document.forms["Mangoform"];
  //Get a reference to the select id="qtyB"

  var QuantityB = theForm.elements["qtyB"];
  if (QuantityB == null || QuantityB === false) {
    var totalpkgPriceB = 0;
    return totalpkgPriceB;
  } else {
    var totalpkgPriceB = 12.99 * QuantityB.value;
    return totalpkgPriceB;
  }
}

function getpkgPriceC() {

  //Get a reference to the form id="Mangoform"
  var theForm = document.forms["Mangoform"];
  //Get a reference to the select id="qtyC"

  var QuantityC = theForm.elements["qtyC"];
  if (QuantityC == null || QuantityC === false) {
    var totalpkgPriceC = 0;
    return totapkgPriceC;
  } else {
    var totalpkgPriceC = 17.99 * QuantityC.value;
    return totalpkgPriceC;
  }
}

function calculateTotal() {

  var TotalpkgPrice = getpkgPriceA() + getpkgPriceB() + getpkgPriceC() + 2;
  var divobj = document.getElementById('totalprice');
  divobj.style.display = 'block';
  divobj.innerHTML = "Your Total: £" + TotalpkgPrice.toFixed(2);
}

function hideTotal() {

  var divobj = document.getElementById('totalprice');
  divobj.style.display = 'none';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="Mangoform">
  <div>
    <div>
      <div>
        <span>
                Small: 1.3kg
            </span>
        <input type="number" id="qtyA" name="qtyA" placeholder="Quantity" onchange="calculateTotal();" min="1" max="100">
      </div>
      </br>
      <div>
        <span>
            Large: 3.3kg
        </span>
        <input type="number" id="qtyB" name="qtyB" placeholder="Quantity" onchange="calculateTotal();" min="1" max="100">
      </div>
      </br>
      <div>
        <span>
                Small: 5.0kg
            </span>
        <input type="number" id="qtyC" name="qtyC" placeholder="Quantity" onchange="calculateTotal();" min="1" max="100">
      </div>
    </div>
  </div>
  <span id="totalprice" name='totalprice'>
            Your Total:
        </span>

  <div>
    <input name="submit" type="button" value="submit" onclick="calculateTotal();">
  </div>

</form>

</body>

</html></code>```

As it was pointed out previously with @Saurabh code. The other reason might be the missing + sign in divobj.innerHTML = "Your Total: £" TotalpkgPrice.toFixed(2)  ; where it has to be corrected to divobj.innerHTML = "Your Total: £" + TotalpkgPrice.toFixed(2)  ;

Body:
I am trying to calculate three values using JS, but the total is not being calculated. it gets values from the form elements and then function calculateTotal() is called onchange. But the total is not being displayed.
*I am new on stackoverflow, please be kind!

I was trying to use method Post on the form, removed it.
Also removed any styling.

function getpkgPriceA() {
  //Get a reference to the form id="Mangoform"
  var theForm = document.forms["Mangoform"];
  //Get a reference to the select id="qtyA"
  var QuantityA = theForm.elements["qtyA"];
  if (QuantityA == null || QuantityA === false) {
    var totalpkgPriceA = 0;
    return totalpkgPriceA;
  } else {
    var totalpkgPriceA = 5.99 * QuantityA.value;
    return totalpkgPriceA;
  }
}

function getpkgPriceB() {
  //Get a reference to the form id="Mangoform"
  var theForm = document.forms["Mangoform"];
  //Get a reference to the select id="qtyB"
  var QuantityB = theForm.elements["qtyB"];
  if (QuantityB == null || QuantityB === false) {
    var totalpkgPriceB = 0;
    return totalpkgPriceB;
  } else {
    var totalpkgPriceB = 12.99 * QuantityB.value;
    return totalpkgPriceB;
  }
}

function getpkgPriceC() {
  //Get a reference to the form id="Mangoform"
  var theForm = document.forms["Mangoform"];
  //Get a reference to the select id="qtyC"
  var QuantityC = theForm.elements["qtyC"];
  if (QuantityC == null || QuantityC === false) {
    var totalpkgPriceC = 0;
    return totapkgPriceC;
  } else {
    var totalpkgPriceC = 17.99 * QuantityC.value;
    return totalpkgPriceC;
  }
}

function calculateTotal() {

  var TotalpkgPrice = getpkgPriceA() + getpkgPriceB() + getpkgPriceC() + 2;
  //display the result
  var divobj = document.getElementById('totalprice');
  divobj.style.display = 'block';
  divobj.innerHTML = "Your Total: £"
  TotalpkgPrice.toFixed(2);
}

function hideTotal() {
  var divobj = document.getElementById('totalprice');
  divobj.style.display = 'none';
}

<form action="#" id="Mangoform">

        Small: 1.3kg
        <input type="number" id="qtyA" name="qtyA" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100">

        Large: 3.3kg
        <input type="number" id="qtyB" name="qtyB" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100">

        Small: 5.0kg
        <input type="number" id="qtyC" name="qtyC" placeholder="Quantity" onchange="calculateTotal()" min="1" max="100">

  Your Total:

    <input name="submit" type="submit" value="submit" onclick="calculateTotal()">

</form>

if value in qtyA=1, qtyB=1 and qtyC=1 and adding 2 then total should be displayed

as 38.97

(5.99*1)+(12.99*1)+(17.99*1)+2=38.97

if qtyA=2, qtyB=2 and qtyC=3 adding 2
(5.99*2)+(12.99*2)+(17.99*3)+2=93.93

Please point out the mistake. Thanks.

Body:
function getpkgPriceA() {

  //Get a reference to the form id="Mangoform"
  var theForm = document.forms["Mangoform"];
  //Get a reference to the select id="qtyA"

  var QuantityA = theForm.elements["qtyA"];
  if (QuantityA == null || QuantityA === false) {
    var totalpkgPriceA = 0;
    return totalpkgPriceA;
  } else {
    var totalpkgPriceA = 5.99 * QuantityA.value;
    return totalpkgPriceA;
  }
}

function getpkgPriceB() {

  //Get a reference to the form id="Mangoform"
  var theForm = document.forms["Mangoform"];
  //Get a reference to the select id="qtyB"

  var QuantityB = theForm.elements["qtyB"];
  if (QuantityB == null || QuantityB === false) {
    var totalpkgPriceB = 0;
    return totalpkgPriceB;
  } else {
    var totalpkgPriceB = 12.99 * QuantityB.value;
    return totalpkgPriceB;
  }
}

function getpkgPriceC() {

  //Get a reference to the form id="Mangoform"
  var theForm = document.forms["Mangoform"];
  //Get a reference to the select id="qtyC"

  var QuantityC = theForm.elements["qtyC"];
  if (QuantityC == null || QuantityC === false) {
    var totalpkgPriceC = 0;
    return totapkgPriceC;
  } else {
    var totalpkgPriceC = 17.99 * QuantityC.value;
    return totalpkgPriceC;
  }
}

function calculateTotal() {

  var TotalpkgPrice = getpkgPriceA() + getpkgPriceB() + getpkgPriceC() + 2;
  var divobj = document.getElementById('totalprice');
  divobj.style.display = 'block';
  divobj.innerHTML = "Your Total: £" + TotalpkgPrice.toFixed(2);
}

function hideTotal() {

  var divobj = document.getElementById('totalprice');
  divobj.style.display = 'none';
}

<form id="Mangoform">
  <div>
    <div>
      <div>
        <span>
                Small: 1.3kg
            </span>
        <input type="number" id="qtyA" name="qtyA" placeholder="Quantity" onchange="calculateTotal();" min="1" max="100">
      </div>
      </br>
      <div>
        <span>
            Large: 3.3kg
        </span>
        <input type="number" id="qtyB" name="qtyB" placeholder="Quantity" onchange="calculateTotal();" min="1" max="100">
      </div>
      </br>
      <div>
        <span>
                Small: 5.0kg
            </span>
        <input type="number" id="qtyC" name="qtyC" placeholder="Quantity" onchange="calculateTotal();" min="1" max="100">
      </div>
    </div>
  </div>
  <span id="totalprice" name='totalprice'>
            Your Total:
        </span>

  <div>
    <input name="submit" type="button" value="submit" onclick="calculateTotal();">
  </div>

</form>

</body>

</html>

As it was pointed out previously with @Saurabh code. The other reason might be the missing + sign in divobj.innerHTML = "Your Total: £" TotalpkgPrice.toFixed(2)  ; where it has to be corrected to divobj.innerHTML = "Your Total: £" + TotalpkgPrice.toFixed(2)  ;


问:
How to? Insert current date from Android into mySQL database using Retrofit2
Trying to insert Current date from android to mysql via Retrofit. The date is showing in the mysql database as 0000-00-00. I've read over multiple threads on SO on this topic and tried to apply the answers but so far I have not been successful. Please see the below code snippets for context.

PHP CODE:

```<code><?php

include('conn.php');

$userId = $_POST['userId'];
$moodBefore = $_POST['moodBefore'];
$automaticThought = $_POST['automaticThought'];
$distortions = $_POST['distortions'];
$challengeThought = $_POST['challengeThought'];
$alternativeThought = $_POST['alternativeThought'];
$moodAfter = $_POST['moodAfter'];
$posted = $_POST['posted'];

$insert = "INSERT INTO Cbt ( userId, moodBefore,   automaticThought, distortions, challengeThought, alternativeThought, moodAfter, posted) VALUES
('$userId','$moodBefore', '$automaticThought', '$distortions', '$challengeThought', '$alternativeThought', '$moodAfter', '$posted')";

  $resultinsert = $conn -> query($insert);
              if(!$resultinsert){
                  echo $conn->error;
        }
 ?>
</code>```

RETROFIT API CODE:

```<code>public interface Api {

    @FormUrlEncoded
    @POST("insert.php")
    Call<ResponseBody> insertLog(
            @Field("userId") int userId,
            @Field("moodBefore") int moodBefore,
            @Field("automaticThought") String automaticThought,
            @Field("distortions") int distortions,
            @Field("challengeThought") String challengeThought,
            @Field("alternativeThought") String alternativeThought,
            @Field("moodAfter") int moodAfter,
            @Field("posted") String date
    );
</code>```

JAVA CODE:

```<code>String posted = new SimpleDateFormat("ddMMyyyy").format(new Date());

case R.id.nextBtnMoodPage:
                if (hasSelected) {

                    Call<ResponseBody> call = RetrofitClient
                            .getInstance()
                            .getApi()
                            .insertLog(userId, moodBefore, automaticThoughtString, distortions, challengeThoughtString, alternativeThoughtString, moodAfter, posted);

                    call.enqueue(new Callback<ResponseBody>() {.....and so on
</code>```

I would like the date to insert succesfully and not show 0000-00-00
If I could also make the date show as DD-MM-YYYY that would be even better.

答:
This worked in the Java code, all other parts of the code stay the same</p>

```<code>private Date currentDate() {
    final Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, 0);
    return cal.getTime();
}

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
String posted = dateFormat.format(currentDate());
</code>```

Body:
Trying to insert Current date from android to mysql via Retrofit. The date is showing in the mysql database as 0000-00-00. I've read over multiple threads on SO on this topic and tried to apply the answers but so far I have not been successful. Please see the below code snippets for context.

PHP CODE:

<?php

include('conn.php');

$userId = $_POST['userId'];
$moodBefore = $_POST['moodBefore'];
$automaticThought = $_POST['automaticThought'];
$distortions = $_POST['distortions'];
$challengeThought = $_POST['challengeThought'];
$alternativeThought = $_POST['alternativeThought'];
$moodAfter = $_POST['moodAfter'];
$posted = $_POST['posted'];

$insert = "INSERT INTO Cbt ( userId, moodBefore,   automaticThought, distortions, challengeThought, alternativeThought, moodAfter, posted) VALUES
('$userId','$moodBefore', '$automaticThought', '$distortions', '$challengeThought', '$alternativeThought', '$moodAfter', '$posted')";

  $resultinsert = $conn -> query($insert);
              if(!$resultinsert){
                  echo $conn->error;
        }
 ?>

RETROFIT API CODE:

public interface Api {

    @FormUrlEncoded
    @POST("insert.php")
    Call<ResponseBody> insertLog(
            @Field("userId") int userId,
            @Field("moodBefore") int moodBefore,
            @Field("automaticThought") String automaticThought,
            @Field("distortions") int distortions,
            @Field("challengeThought") String challengeThought,
            @Field("alternativeThought") String alternativeThought,
            @Field("moodAfter") int moodAfter,
            @Field("posted") String date
    );

JAVA CODE:

String posted = new SimpleDateFormat("ddMMyyyy").format(new Date());

case R.id.nextBtnMoodPage:
                if (hasSelected) {

                    Call<ResponseBody> call = RetrofitClient
                            .getInstance()
                            .getApi()
                            .insertLog(userId, moodBefore, automaticThoughtString, distortions, challengeThoughtString, alternativeThoughtString, moodAfter, posted);

                    call.enqueue(new Callback<ResponseBody>() {.....and so on

I would like the date to insert succesfully and not show 0000-00-00
If I could also make the date show as DD-MM-YYYY that would be even better.

Body:
This worked in the Java code, all other parts of the code stay the same

private Date currentDate() {
    final Calendar cal = Calendar.getInstance();
    cal.add(Calendar.DATE, 0);
    return cal.getTime();
}

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
String posted = dateFormat.format(currentDate());