问:
Devise sets current_user to nil after I change this users password and sign them back in
Here is the code I'm trying to use in my controller:

profiles_controller.rb:

```<code>class ProfilesController < ApplicationController
  ...

  def update

    respond_to do |format|
      # assume valid data sent (I've already tested for this)
      if @user.update(user_params)
        # password_reset? check's parameter passed to action that a check box was
        # checked (which enables/disables password/confirmation fields. If unchecked,
        # fields are disabled and no password parameters are sent to this action.
        # @user was set to current_user in a before_action already
        # inspecting @user at this point returns the same thing as current_user here
        sign_in(:user, @user) if password_reset?
        # current_user is still set to @user and is valid

        # after redirection current_user becomes nil
        format.html {
          redirect_to home_path, notice: 'Your profile was successfully updated.'
        }
      else
        format.html { render :edit }
      end
    end
  end
  ...
private
  # Never trust parameters from the scary internet, only allow the white list through.
  def user_params
    @user_params ||= params.require(:user).permit(:first_name, :last_name, :email, :phone, :password, :password_confirmation, :reset_password)
  end

  def password_reset?
    @user_params["reset_password"] == "1"
  end
end
</code>```

application_controller.rb:

```<code>class ApplicationController < ActionController::Base
...

private
...
  def require_user
    logger.debug "IN REQUIRE_USER, CURRENT_USER IS: #{current_user.inspect}"
    unless current_user
      store_location
      redirect_to new_user_session_url, notice: "That url doesn't exist."
      return false
    end
  end

  def require_admin
    # this line will actually log a user in
    #sign_in(:user, User.first) unless current_user
    logger.debug "IN REQUIRE_ADMIN, CURRENT_USER IS: #{current_user.inspect}"
    unless current_user && current_user.is_admin?
      redirect_to(home_path, notice: "That url doesn't exist.") and return false
    end
  end
...
end
</code>```

development.log:

```<code>Started PATCH "/profile" for 127.0.0.1 at 2019-05-28 10:38:45 -0700
Processing by ProfilesController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"....", "user"=>{....}, "commit"=>"Update Profile"}
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/application_controller.rb:47
IN REQUIRE_USER, CURRENT_USER IS: #<User id: 1 ....>
   (0.1ms)  begin transaction
  ↳ app/controllers/profiles_controller.rb:16
  User Exists (0.4ms)  SELECT  1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER(?) AND "users"."id" != ? LIMIT ?  [["email", "...."], ["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/profiles_controller.rb:16
  User Update (0.3ms)  UPDATE "users" SET "encrypted_password" = ?, "updated_at" = ? WHERE "users"."id" = ?  [["encrypted_password", "$2a$11...."], ["updated_at", "2019-05-28 17:38:45.346414"], ["id", 1]]
  ↳ app/controllers/profiles_controller.rb:16
   (2.3ms)  commit transaction
  ↳ app/controllers/profiles_controller.rb:16
PASSWORDS PASSED IN SO USER PASSWORD CHANGE OCCURRED
REDIRECTING TO HOME PATH
Redirected to http://localhost:3000/admin
Completed 302 Found in 121ms (ActiveRecord: 3.2ms)

Started GET "/admin" for 127.0.0.1 at 2019-05-28 10:38:45 -0700
Processing by Admin::PagesController#index as HTML
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/application_controller.rb:65
IN REQUIRE_ADMIN, CURRENT_USER IS: nil
Redirected to http://localhost:3000/
Filter chain halted as :require_admin rendered or redirected
Completed 302 Found in 2ms (ActiveRecord: 0.2ms)

Started GET "/" for 127.0.0.1 at 2019-05-28 10:38:45 -0700
Processing by PagesController#index as HTML
  Rendering pages/index.html.erb within layouts/application
  Rendered pages/index.html.erb within layouts/application (0.7ms)
  Rendered application/_navigation.html.erb (1.7ms)
  Rendered application/_alert.html.erb (0.3ms)
Completed 200 OK in 1152ms (Views: 1151.2ms | ActiveRecord: 0.0ms)
</code>```

I've searched around and seen by_pass: true being passed to sign_in but that doesn't help. I've also tried @current_user = @user once I've signed the user in (@current_user is the direct instance variable for the Devise controller btw) and that does not help either.

Any ideas?

答:
Devise ignores signin if the user is already signed in, try:

if @user.saved_change_to_encrypted_password? # for rails 5+, for previous - .encrypted_password_changed?
  sign_in @user, force: true
end
```

Body:
Here is the code I'm trying to use in my controller:

profiles_controller.rb:

class ProfilesController < ApplicationController
  ...

  def update

    respond_to do |format|
      # assume valid data sent (I've already tested for this)
      if @user.update(user_params)
        # password_reset? check's parameter passed to action that a check box was
        # checked (which enables/disables password/confirmation fields. If unchecked,
        # fields are disabled and no password parameters are sent to this action.
        # @user was set to current_user in a before_action already
        # inspecting @user at this point returns the same thing as current_user here
        sign_in(:user, @user) if password_reset?
        # current_user is still set to @user and is valid

        # after redirection current_user becomes nil
        format.html {
          redirect_to home_path, notice: 'Your profile was successfully updated.'
        }
      else
        format.html { render :edit }
      end
    end
  end
  ...
private
  # Never trust parameters from the scary internet, only allow the white list through.
  def user_params
    @user_params ||= params.require(:user).permit(:first_name, :last_name, :email, :phone, :password, :password_confirmation, :reset_password)
  end

  def password_reset?
    @user_params["reset_password"] == "1"
  end
end

application_controller.rb:

class ApplicationController < ActionController::Base
...

private
...
  def require_user
    logger.debug "IN REQUIRE_USER, CURRENT_USER IS: #{current_user.inspect}"
    unless current_user
      store_location
      redirect_to new_user_session_url, notice: "That url doesn't exist."
      return false
    end
  end

  def require_admin
    # this line will actually log a user in
    #sign_in(:user, User.first) unless current_user
    logger.debug "IN REQUIRE_ADMIN, CURRENT_USER IS: #{current_user.inspect}"
    unless current_user && current_user.is_admin?
      redirect_to(home_path, notice: "That url doesn't exist.") and return false
    end
  end
...
end

development.log:

Started PATCH "/profile" for 127.0.0.1 at 2019-05-28 10:38:45 -0700
Processing by ProfilesController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"....", "user"=>{....}, "commit"=>"Update Profile"}
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/application_controller.rb:47
IN REQUIRE_USER, CURRENT_USER IS: #<User id: 1 ....>
   (0.1ms)  begin transaction
  ↳ app/controllers/profiles_controller.rb:16
  User Exists (0.4ms)  SELECT  1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER(?) AND "users"."id" != ? LIMIT ?  [["email", "...."], ["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/profiles_controller.rb:16
  User Update (0.3ms)  UPDATE "users" SET "encrypted_password" = ?, "updated_at" = ? WHERE "users"."id" = ?  [["encrypted_password", "$2a$11...."], ["updated_at", "2019-05-28 17:38:45.346414"], ["id", 1]]
  ↳ app/controllers/profiles_controller.rb:16
   (2.3ms)  commit transaction
  ↳ app/controllers/profiles_controller.rb:16
PASSWORDS PASSED IN SO USER PASSWORD CHANGE OCCURRED
REDIRECTING TO HOME PATH
Redirected to http://localhost:3000/admin
Completed 302 Found in 121ms (ActiveRecord: 3.2ms)

Started GET "/admin" for 127.0.0.1 at 2019-05-28 10:38:45 -0700
Processing by Admin::PagesController#index as HTML
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ?  [["id", 1], ["LIMIT", 1]]
  ↳ app/controllers/application_controller.rb:65
IN REQUIRE_ADMIN, CURRENT_USER IS: nil
Redirected to http://localhost:3000/
Filter chain halted as :require_admin rendered or redirected
Completed 302 Found in 2ms (ActiveRecord: 0.2ms)

Started GET "/" for 127.0.0.1 at 2019-05-28 10:38:45 -0700
Processing by PagesController#index as HTML
  Rendering pages/index.html.erb within layouts/application
  Rendered pages/index.html.erb within layouts/application (0.7ms)
  Rendered application/_navigation.html.erb (1.7ms)
  Rendered application/_alert.html.erb (0.3ms)
Completed 200 OK in 1152ms (Views: 1151.2ms | ActiveRecord: 0.0ms)

I've searched around and seen by_pass: true being passed to sign_in but that doesn't help. I've also tried @current_user = @user once I've signed the user in (@current_user is the direct instance variable for the Devise controller btw) and that does not help either.

Any ideas?


来源: stackexchange

问:
SSIS XMl processing
For my job I do very big imports of (product) data. Recently we started using SSIS and it sure works better then custom .net import tools. Still after 3 projects we figured out it's more efficient to use an scripttask with c# xpath and sql statements then to use XML source and merge joins in a dataflow.

Problems with a dataflow

Sometimes the xml cannot read from a variable

It depends too much on a fixed definition of XML (the xsd needs to    be known)

When definitions change a whole needs to be altered

To specific type handling; UINT and INT arn't the same

Not easy to debug and step through as C# code

Can anyone share their SSIS XML import stories

答: I work "all the way" with XML in SQL Server and mainly it is import feature in some of my projects.I do not use SSIS XML source because of limitation of XML structure. As example, it is not possible to import data from "Excel XML", where not only data but column names are as values. To prepare this kind of import, i use TSQL code. Maybe for this example you can use third-party components, but not all customers want to pay for that.))</p>

ContentLicense: CC BY-SA 2.5

Title: SSIS XMl processing

ContentLicense: CC BY-SA 3.0


问:
Tests pass when run individually but not when the whole test class run
I have solved a topCoder problem for which all the tests pass when I run them on their own. Nonetheless when I run the whole test class some of them fail. Could you, please, help me identify the reason for this behaviour? Here is my class and my tests:

```<code> package com.topcoder.div2.stage1;

import java.util.Arrays;

public class GameOfStones {
    private int iterations = 0;
    public int count(int[] stones){
        int result = checkEquality(stones);
        return result;
    }

    private int checkEquality(int[] stones){
        int count = 0;
        int sum = 0;
        for(int k = 0; k< stones.length;k++){
            sum += stones[k];
        }
        if(stones.length > 0) {
            for (int i = 0; i < sum; i++) {
                Arrays.sort(stones);
                if(stones[stones.length-1] != 3) {
                    int j = 0;
                    while (j < stones.length - 1) {
                        if (stones[j] == stones[j + 1]) {
                            count++;
                        }
                        j++;
                    }
                    if (count == stones.length - 1) {
                        return iterations;
                    }
                    stones[0] = stones[0] + 2;
                    stones[stones.length - 1] = stones[stones.length - 1] - 2;
                    iterations++;
                    count = 0;
                }
            }
        }
        return -1;
    }
}
</code>```

Test:

```<code>package com.topcoder.div2.stage1;

import org.testng.annotations.Test;

import static org.testng.Assert.assertEquals;

public class GameOfStonesTest {
    private GameOfStones gameOfStones = new GameOfStones();

    @Test
    public void test1() {
        int expected = 0;
        int[] given = {17};

        int actual = gameOfStones.count(given);

        assertEquals(expected, actual);
    }

    @Test
    public void test2() {
        int expected = 3;
        int[] given ={7, 15, 9, 5};

        int actual = gameOfStones.count(given);
        assertEquals(actual, expected);
    }

    @Test
    public void test3() {
        int expected = -1;
        int[] given ={2, 8, 4};

        int actual = gameOfStones.count(given);
        assertEquals(actual, expected);
    }

    @Test
    public void test4() {
        int expected = -1;
        int[] given ={10, 15, 20, 12, 1, 20};

        int actual = gameOfStones.count(given);
        assertEquals(actual, expected);
    }

    @Test
    public void test5(){
        int expected = 277;
        int[] given ={17, 1, 27, 29, 13, 1, 27, 3, 19, 3, 25, 1, 11, 9, 7, 17, 31, 25, 5, 11, 31, 9,
                15, 3, 3, 3, 11, 11, 1, 41, 5, 95, 7, 3, 41, 31, 7, 13, 15, 5, 17, 3, 9, 3, 11,
                27, 1, 23, 15, 5, 43, 11, 17, 7, 1, 3, 13, 69, 3, 43, 21, 1, 25, 1, 3, 11, 5, 43,
                13, 7, 15, 1, 1, 55, 37, 9, 5, 7, 21, 3, 23, 15, 1, 9, 3, 35, 13, 17, 7, 17, 27, 5,
                9, 19, 13, 1, 1, 1, 29};
        int actual = gameOfStones.count(given);
        assertEquals(actual, expected);
    }

    @Test
     public void test6(){
        int expected = 539;
        int[] given ={1, 29, 11, 35, 57, 15, 85, 19, 5, 47, 53, 5, 63, 19, 13, 63, 27, 43, 53, 75, 67, 93, 33, 31, 47, 3,
                63, 17, 11, 53, 35, 23, 17, 45, 31, 19, 63, 75, 5, 3, 49, 19, 11, 89, 21, 69,
                71, 5, 45, 81, 31, 13, 11, 19, 7, 99, 33, 63, 19, 57, 73, 29, 35, 9, 47,
                1, 17, 7, 13, 31, 5, 85, 95, 23, 45, 65, 63, 41, 81, 33, 45, 1, 15,
                45, 19, 87, 51, 7, 13, 39, 1, 59, 29, 35, 1, 43};
        int actual = gameOfStones.count(given);
        assertEquals(actual, expected);
    }

    @Test
    public void test7() {
        int expected = 0;
        int[] given ={100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
                100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
                100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
                100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
                100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
                100, 100};
        int actual = gameOfStones.count(given);
        assertEquals(actual, expected);
    }

    @Test
    public void test8() {
        int expected = 11;
        int[] given ={3, 5, 21, 31};
        int actual = gameOfStones.count(given);
        assertEquals(actual, expected);
    }

    @Test
    public void test9() {
        int expected = 13;
        int[] given ={44, 6, 46};
        int actual = gameOfStones.count(given);
        assertEquals(actual, expected);
    }

}
</code>```

P.S if you know any suggestions of improving the solution you are more than welcome to include them in your answer.

答:
I had same issue. I needed to mock a logger, which was a static field. So eventually class loader creates only a single instance of the static field during the first invocation of a class under the test and disregards all further mocking and stubbing. When run separately, test was green, because the logger was initialized and loaded as expected, but when run all together, with other test methods, it got initialized as a concrete object, not a mock. Workaround:

create @BeforeClass method to ensure that the right instance of static field will be created in the first place:

    @BeforeClass
    public static void setupBeforeClass() {
      PowerMockito.mockStatic(LoggerFactory.class);
      loggerMock = mock(Logger.class);
      when(LoggerFactory.getLogger(any(Class.class))).thenReturn(loggerMock);
   }
```

<ul>
<li>Interactions on the mock are getting accumulated from different test executions. Therefore, to be sure that you get a clean instance of the mock on each test method execution, reset the mock whether in <code>@Before</code> or <code>@After</code> method:</li>
</ul>

<pre class="lang-java prettyprint-override"><code>      @Before
      public void setup() {

        // Reset interactions on the mocked logger
        Mockito.reset(loggerMock);

      }
</code>```

Note, that in my example I used PowerMock so you need a corresponding runner @RunWith(PowerMockRunner.class) and @PrepareForTest({LoggerFactory.class, MyClass.class)} statements.

Body:
I have solved a topCoder problem for which all the tests pass when I run them on their own. Nonetheless when I run the whole test class some of them fail. Could you, please, help me identify the reason for this behaviour? Here is my class and my tests:

 package com.topcoder.div2.stage1;

import java.util.Arrays;

public class GameOfStones {
    private int iterations = 0;
    public int count(int[] stones){
        int result = checkEquality(stones);
        return result;
    }

    private int checkEquality(int[] stones){
        int count = 0;
        int sum = 0;
        for(int k = 0; k< stones.length;k++){
            sum += stones[k];
        }
        if(stones.length > 0) {
            for (int i = 0; i < sum; i++) {
                Arrays.sort(stones);
                if(stones[stones.length-1] != 3) {
                    int j = 0;
                    while (j < stones.length - 1) {
                        if (stones[j] == stones[j + 1]) {
                            count++;
                        }
                        j++;
                    }
                    if (count == stones.length - 1) {
                        return iterations;
                    }
                    stones[0] = stones[0] + 2;
                    stones[stones.length - 1] = stones[stones.length - 1] - 2;
                    iterations++;
                    count = 0;
                }
            }
        }
        return -1;
    }
}

Test:

package com.topcoder.div2.stage1;

import org.testng.annotations.Test;

import static org.testng.Assert.assertEquals;

public class GameOfStonesTest {
    private GameOfStones gameOfStones = new GameOfStones();

    @Test
    public void test1() {
        int expected = 0;
        int[] given = {17};

        int actual = gameOfStones.count(given);

        assertEquals(expected, actual);
    }

    @Test
    public void test2() {
        int expected = 3;
        int[] given ={7, 15, 9, 5};

        int actual = gameOfStones.count(given);
        assertEquals(actual, expected);
    }

    @Test
    public void test3() {
        int expected = -1;
        int[] given ={2, 8, 4};

        int actual = gameOfStones.count(given);
        assertEquals(actual, expected);
    }

    @Test
    public void test4() {
        int expected = -1;
        int[] given ={10, 15, 20, 12, 1, 20};

        int actual = gameOfStones.count(given);
        assertEquals(actual, expected);
    }

    @Test
    public void test5(){
        int expected = 277;
        int[] given ={17, 1, 27, 29, 13, 1, 27, 3, 19, 3, 25, 1, 11, 9, 7, 17, 31, 25, 5, 11, 31, 9,
                15, 3, 3, 3, 11, 11, 1, 41, 5, 95, 7, 3, 41, 31, 7, 13, 15, 5, 17, 3, 9, 3, 11,
                27, 1, 23, 15, 5, 43, 11, 17, 7, 1, 3, 13, 69, 3, 43, 21, 1, 25, 1, 3, 11, 5, 43,
                13, 7, 15, 1, 1, 55, 37, 9, 5, 7, 21, 3, 23, 15, 1, 9, 3, 35, 13, 17, 7, 17, 27, 5,
                9, 19, 13, 1, 1, 1, 29};
        int actual = gameOfStones.count(given);
        assertEquals(actual, expected);
    }

    @Test
     public void test6(){
        int expected = 539;
        int[] given ={1, 29, 11, 35, 57, 15, 85, 19, 5, 47, 53, 5, 63, 19, 13, 63, 27, 43, 53, 75, 67, 93, 33, 31, 47, 3,
                63, 17, 11, 53, 35, 23, 17, 45, 31, 19, 63, 75, 5, 3, 49, 19, 11, 89, 21, 69,
                71, 5, 45, 81, 31, 13, 11, 19, 7, 99, 33, 63, 19, 57, 73, 29, 35, 9, 47,
                1, 17, 7, 13, 31, 5, 85, 95, 23, 45, 65, 63, 41, 81, 33, 45, 1, 15,
                45, 19, 87, 51, 7, 13, 39, 1, 59, 29, 35, 1, 43};
        int actual = gameOfStones.count(given);
        assertEquals(actual, expected);
    }

    @Test
    public void test7() {
        int expected = 0;
        int[] given ={100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
                100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
                100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
                100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
                100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100, 100,
                100, 100};
        int actual = gameOfStones.count(given);
        assertEquals(actual, expected);
    }

    @Test
    public void test8() {
        int expected = 11;
        int[] given ={3, 5, 21, 31};
        int actual = gameOfStones.count(given);
        assertEquals(actual, expected);
    }

    @Test
    public void test9() {
        int expected = 13;
        int[] given ={44, 6, 46};
        int actual = gameOfStones.count(given);
        assertEquals(actual, expected);
    }

}

P.S if you know any suggestions of improving the solution you are more than welcome to include them in your answer.

Body:
I had same issue. I needed to mock a logger, which was a static field. So eventually class loader creates only a single instance of the static field during the first invocation of a class under the test and disregards all further mocking and stubbing. When run separately, test was green, because the logger was initialized and loaded as expected, but when run all together, with other test methods, it got initialized as a concrete object, not a mock. Workaround:

create @BeforeClass method to ensure that the right instance of static field will be created in the first place:

    @BeforeClass
    public static void setupBeforeClass() {
      PowerMockito.mockStatic(LoggerFactory.class);
      loggerMock = mock(Logger.class);
      when(LoggerFactory.getLogger(any(Class.class))).thenReturn(loggerMock);
   }

Interactions on the mock are getting accumulated from different test executions. Therefore, to be sure that you get a clean instance of the mock on each test method execution, reset the mock whether in @Before or @After method:

      @Before
      public void setup() {

        // Reset interactions on the mocked logger
        Mockito.reset(loggerMock);

      }

Note, that in my example I used PowerMock so you need a corresponding runner @RunWith(PowerMockRunner.class) and @PrepareForTest({LoggerFactory.class, MyClass.class)} statements.

ContentLicense: CC BY-SA 4.0


问:
How can I format the date from mysql (I'm using node.js)?
I'm using node.js to select info from my mysql database and I have a datetime column, but I'm not getting the format I want.

This is my sql code
SELECT id, data, titulo, subtitulo, texto, DATE(datahora_cadastro) as data FROM sig_noticias

I need the data to be like this: DD/MM/YYYY
But I'm getting this: Thu Mar 30 2017 00:00:00 GMT-0300 (GMT-03:00)

答:
Easiest way to format dates in Javascript is by far using a modern date / time library. I personally use MomentJS and it works well. I highly recommend this solution if you plan on working with dates in even just a few areas of your app.

Using moment, you could simply call moment(myDate).format("DD/MM/YYYY");.

If you really want to stick to pure Javascript, however, here's how to get the format you want:

```<code>const formattedDate = `${myDate.getDate() + 1}/${myDate.getMonth() + 1}/${myDate.getFullYear()}`;
</code>```

Javascript's built-in date functions are pretty confusing. Here, for instance, the getDate and getMonth methods return the index of the date / month, and not the actual date / month, so we need to add +1 to those.

Using vanilla Javascript then becomes even harder when dealing with date manipulation (adding, subtracting) and timezones.

Body:
Easiest way to format dates in Javascript is by far using a modern date / time library. I personally use MomentJS and it works well. I highly recommend this solution if you plan on working with dates in even just a few areas of your app.

Using moment, you could simply call moment(myDate).format("DD/MM/YYYY");.

If you really want to stick to pure Javascript, however, here's how to get the format you want:

const formattedDate = `${myDate.getDate() + 1}/${myDate.getMonth() + 1}/${myDate.getFullYear()}`;

Javascript's built-in date functions are pretty confusing. Here, for instance, the getDate and getMonth methods return the index of the date / month, and not the actual date / month, so we need to add +1 to those.

Using vanilla Javascript then becomes even harder when dealing with date manipulation (adding, subtracting) and timezones.


问:
Pattern Matching In SQL where characters appears anywhere but in sequence
I'm attempting to write a query to fix invalid email formats. The invalid email format I am getting is of the form first@name_company@com.

The characters always appear as '@' '_' '@' in that sequence.

If this is the format then I am replacing @ with . and _ with @ to get a correct format as:

```<code>first.name@company.com
</code>```

I am considering a case condition like this:

```<code>When @email like '[a-z,0-9,_,-,@]_[a-z,0-9,_,-@]'  THEN replace(replace(replace(@email,'@','.'),'_','@'))
</code>```

This only seems to work if I put "_" as a wildcard like this '[a-z,0-9,_,-,@]%_%[a-z,0-9,_,-@]'

答:
SQL Server is quite limited in pattern matching, but you can do something like this:

```<code>where email like '%_@_%' and      -- @ with something before and after
      email not like '%@%@%' and  -- not two @s
      email not like '%[^-_@.a-zA-Z0-9]%'  -- has no obvious bad characters
</code>```

This is not a guarantee of a good email, but it catches many problems.

Body:
I'm attempting to write a query to fix invalid email formats. The invalid email format I am getting is of the form first@name_company@com.

The characters always appear as '@' '_' '@' in that sequence.

If this is the format then I am replacing @ with . and _ with @ to get a correct format as:

first.name@company.com

I am considering a case condition like this:

When @email like '[a-z,0-9,_,-,@]_[a-z,0-9,_,-@]'  THEN replace(replace(replace(@email,'@','.'),'_','@'))

This only seems to work if I put "_" as a wildcard like this '[a-z,0-9,_,-,@]%_%[a-z,0-9,_,-@]'

Body:
SQL Server is quite limited in pattern matching, but you can do something like this:

where email like '%_@_%' and      -- @ with something before and after
      email not like '%@%@%' and  -- not two @s
      email not like '%[^-_@.a-zA-Z0-9]%'  -- has no obvious bad characters

This is not a guarantee of a good email, but it catches many problems.


问:
Flutter Failed to upload Multiple images obtained from multi_image_picker
I've been successful in obtaining multiple images using the multi_image_picker but failed to upload the images to firebase storage. Am requesting for help as regards saving the images to firebase storage and returning the urls.

Ive posted my code below, Thanks.

```<code>import 'package:flutter/material.dart';
import 'dart:async';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/services.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:mock_data/mock_data.dart';

class PageTwo extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<PageTwo> {
  List<Asset> images = List<Asset>();
  String popop = mockString(50);

  @override
  void initState() {
    super.initState();
  }

  Widget buildGridView() {
    return GridView.count(
      crossAxisCount: 3,
      children: List.generate(images.length, (index) {
        Asset asset = images[index];
        return AssetThumb(
          asset: asset,
          width: 300,
          height: 300,
        );
      }),
    );
  }

  Future saveImage(Asset asset) async {
    String fileName = popop;
    ByteData byteData = await asset.requestOriginal();
    List<int> imageData = byteData.buffer.asUint8List();
    StorageReference ref = FirebaseStorage.instance.ref().child(fileName);
    StorageUploadTask uploadTask = ref.putData(imageData);

    return await (await uploadTask.onComplete).ref.getDownloadURL();
  }

  Future<void> loadAssets() async {
    List<Asset> resultList = List<Asset>();
    try {
      resultList = await MultiImagePicker.pickImages(
          maxImages: 300,
          enableCamera: true,
          selectedAssets: images,
          cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
          materialOptions: MaterialOptions(
            actionBarColor: "#abcdef",
            actionBarTitle: "Example App",
            allViewTitle: "All Photos",
            selectCircleStrokeColor: "#000000",
          ));
    }
    }
    if (!mounted) return;

    setState(() {
      images = resultList;
      _error = error;
    });
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: const Text('Getting pics'),
        ),
        body: Column(
          children: <Widget>[
            RaisedButton(
              child: Text("Pick images"),
              onPressed: loadAssets,
            ),
            RaisedButton(
              child: Text("Save Image"),
              onPressed: () => saveImage,
            ),
            Expanded(
              child: buildGridView(),
            )
          ],
        ),
      ),
    );
  }
}
</code>```

答:
It doesn't look like you're actually doing anything with the URL. Your Future on saveFile doesn't return anything, nor are you placing the result anywhere.

```<code>await (await uploadTask.onComplete).ref.getDownloadURL()
</code>```

Plus, that looks a bit odd to be awaiting an await. You could probably get away with simply cascading the onComplete await. I'm not entirely sure but worth a try.

```<code>await uploadTask.onComplete..ref.getDownloadURL()
</code>```

Furthermore, when I use StorageUploadTask I usually listen to the task to get upload progress and then I add the onComplete portion to get the downloadURL.

Body:
I've been successful in obtaining multiple images using the multi_image_picker but failed to upload the images to firebase storage. Am requesting for help as regards saving the images to firebase storage and returning the urls.

Ive posted my code below, Thanks.

import 'package:flutter/material.dart';
import 'dart:async';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/services.dart';
import 'package:multi_image_picker/multi_image_picker.dart';
import 'package:mock_data/mock_data.dart';

class PageTwo extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<PageTwo> {
  List<Asset> images = List<Asset>();
  String popop = mockString(50);

  @override
  void initState() {
    super.initState();
  }

  Widget buildGridView() {
    return GridView.count(
      crossAxisCount: 3,
      children: List.generate(images.length, (index) {
        Asset asset = images[index];
        return AssetThumb(
          asset: asset,
          width: 300,
          height: 300,
        );
      }),
    );
  }

  Future saveImage(Asset asset) async {
    String fileName = popop;
    ByteData byteData = await asset.requestOriginal();
    List<int> imageData = byteData.buffer.asUint8List();
    StorageReference ref = FirebaseStorage.instance.ref().child(fileName);
    StorageUploadTask uploadTask = ref.putData(imageData);

    return await (await uploadTask.onComplete).ref.getDownloadURL();
  }

  Future<void> loadAssets() async {
    List<Asset> resultList = List<Asset>();
    try {
      resultList = await MultiImagePicker.pickImages(
          maxImages: 300,
          enableCamera: true,
          selectedAssets: images,
          cupertinoOptions: CupertinoOptions(takePhotoIcon: "chat"),
          materialOptions: MaterialOptions(
            actionBarColor: "#abcdef",
            actionBarTitle: "Example App",
            allViewTitle: "All Photos",
            selectCircleStrokeColor: "#000000",
          ));
    }
    }
    if (!mounted) return;

    setState(() {
      images = resultList;
      _error = error;
    });
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new Scaffold(
        appBar: new AppBar(
          title: const Text('Getting pics'),
        ),
        body: Column(
          children: <Widget>[
            RaisedButton(
              child: Text("Pick images"),
              onPressed: loadAssets,
            ),
            RaisedButton(
              child: Text("Save Image"),
              onPressed: () => saveImage,
            ),
            Expanded(
              child: buildGridView(),
            )
          ],
        ),
      ),
    );
  }
}

Body:
It doesn't look like you're actually doing anything with the URL. Your Future on saveFile doesn't return anything, nor are you placing the result anywhere.

await (await uploadTask.onComplete).ref.getDownloadURL()

Plus, that looks a bit odd to be awaiting an await. You could probably get away with simply cascading the onComplete await. I'm not entirely sure but worth a try.

await uploadTask.onComplete..ref.getDownloadURL()

Furthermore, when I use StorageUploadTask I usually listen to the task to get upload progress and then I add the onComplete portion to get the downloadURL.


问:
Nexus 3 | How to create (external) users using Nexus 3 APIs?
I'm trying to create external user on Nexus 3 using nexus 3 APIs. Following are the details:
Posting Groovy Script using: http://localhost:8081/nexus3/service/rest/v1/script

```<code>{
    "name": "d8b3baeb-628a-43cc-9a9c-9a156f399e2",
    "type": "groovy",
    "content": "security.addUser('q018246a', '', '', '', true, 'd8b3baeb-628a-43cc-9a9c-9a156f399ae2', ['abc_test_role Developer Role']);"
}
</code>```

Running Script using: http://localhost:8081/nexus3/service/rest/v1/script/d8b3baeb-628a-43cc-9a9c-9a156f399e2/run

Response:

```<code>{
    "name": "d8b3baeb-628a-43cc-9a9c-9a156f399e2",
    "result": "User{userId='q018246a', firstName='', lastName='', source='default'}"
}
</code>```

Hitting though Postman, all working fine and users getting created. But through Application server it is giving Bad request.

Awkward behavior is, it's letting me create user using postman post script with blank first_name, last_name, email, password, but all these parameters are required on UI.

Another thing, It's showing source as default but how to I ensure source as LDAP?

答:
I assume you're trying to map an LDAP user?  If so, this will work:</p>

```<code>import org.sonatype.nexus.security.role.RoleIdentifier;
import org.sonatype.nexus.security.user.User;

String userId = 'someuser';
String newRoleId = 'nx-admin'

User user = security.securitySystem.getUser(userId, 'LDAP')

if(user != null) {
    RoleIdentifier newRole = new RoleIdentifier('default', newRoleId);
    user.addRole(newRole)
    security.securitySystem.setUsersRoles(user.getUserId(), 'LDAP', user.getRoles());
} else {
    log.warn("No user with ID of $userId found.")
}
</code>```

Body:
I'm trying to create external user on Nexus 3 using nexus 3 APIs. Following are the details:
Posting Groovy Script using: http://localhost:8081/nexus3/service/rest/v1/script

{
    "name": "d8b3baeb-628a-43cc-9a9c-9a156f399e2",
    "type": "groovy",
    "content": "security.addUser('q018246a', '', '', '', true, 'd8b3baeb-628a-43cc-9a9c-9a156f399ae2', ['abc_test_role Developer Role']);"
}

Running Script using: http://localhost:8081/nexus3/service/rest/v1/script/d8b3baeb-628a-43cc-9a9c-9a156f399e2/run

Response:

{
    "name": "d8b3baeb-628a-43cc-9a9c-9a156f399e2",
    "result": "User{userId='q018246a', firstName='', lastName='', source='default'}"
}

Hitting though Postman, all working fine and users getting created. But through Application server it is giving Bad request.

Awkward behavior is, it's letting me create user using postman post script with blank first_name, last_name, email, password, but all these parameters are required on UI.

Another thing, It's showing source as default but how to I ensure source as LDAP?

Body:
I assume you're trying to map an LDAP user?  If so, this will work:

import org.sonatype.nexus.security.role.RoleIdentifier;
import org.sonatype.nexus.security.user.User;

String userId = 'someuser';
String newRoleId = 'nx-admin'

User user = security.securitySystem.getUser(userId, 'LDAP')

if(user != null) {
    RoleIdentifier newRole = new RoleIdentifier('default', newRoleId);
    user.addRole(newRole)
    security.securitySystem.setUsersRoles(user.getUserId(), 'LDAP', user.getRoles());
} else {
    log.warn("No user with ID of $userId found.")
}


问:
How to increase the number of rows of data displayed in a TreeView?
I want to display 500+ entries in a TreeView. The following is the code that I wrote:

```<code>import tkinter.ttk as ttk
from tkinter import *

#entries is a list of lists containing the data I want to display

master = Tk()
tree = ttk.Treeview(master, columns=('Name', 'Quiz 1', 'Quiz 2', 'MidSem'))
tree.heading('#0', text='ID')
tree.heading('#1', text='Name')
tree.heading('#2', text='Quiz 1')
tree.heading('#3', text='Quiz 2 ')
tree.heading('#4', text='MidSem')
tree.column('#1', stretch=YES)
tree.column('#2', stretch=YES)
tree.column('#3', stretch=YES)
tree.column('#4', stretch=YES)
tree.column('#0', stretch=YES)
tree.pack(fill=BOTH)

for entry in entries:
    tree.insert('', 'end', text=entry[0], values=(entry[1], entry[2], entry[3], entry[4]))
</code>```

When I run this code, it seems that I can only see 10 rows of data, even if I resize the window and I'd like to see more than 10 rows of data.
How do I increase the number of rows displayed in this?

答:
you must set expand = 1

```<code>import tkinter.ttk as ttk
from tkinter import *

#entries is a list of lists containing the data I want to display

entries = []

for i in range(0,500):
    args = (i,'Name','Quiz 1', 'Quiz 2', 'MidSem')
    entries.append(args)

master = Tk()
tree = ttk.Treeview(master, columns=('Name', 'Quiz 1', 'Quiz 2', 'MidSem'))
tree.heading('#0', text='ID')
tree.heading('#1', text='Name')
tree.heading('#2', text='Quiz 1')
tree.heading('#3', text='Quiz 2 ')
tree.heading('#4', text='MidSem')
tree.column('#1', stretch=YES)
tree.column('#2', stretch=YES)
tree.column('#3', stretch=YES)
tree.column('#4', stretch=YES)
tree.column('#0', stretch=YES)
tree.pack(fill=BOTH,expand=1)

for entry in entries:
    tree.insert('', 'end', text=entry[0], values=(entry[1], entry[2], entry[3], entry[4]))
</code>```

Body:
I want to display 500+ entries in a TreeView. The following is the code that I wrote:

import tkinter.ttk as ttk
from tkinter import *

#entries is a list of lists containing the data I want to display

master = Tk()
tree = ttk.Treeview(master, columns=('Name', 'Quiz 1', 'Quiz 2', 'MidSem'))
tree.heading('#0', text='ID')
tree.heading('#1', text='Name')
tree.heading('#2', text='Quiz 1')
tree.heading('#3', text='Quiz 2 ')
tree.heading('#4', text='MidSem')
tree.column('#1', stretch=YES)
tree.column('#2', stretch=YES)
tree.column('#3', stretch=YES)
tree.column('#4', stretch=YES)
tree.column('#0', stretch=YES)
tree.pack(fill=BOTH)

for entry in entries:
    tree.insert('', 'end', text=entry[0], values=(entry[1], entry[2], entry[3], entry[4]))

When I run this code, it seems that I can only see 10 rows of data, even if I resize the window and I'd like to see more than 10 rows of data.
How do I increase the number of rows displayed in this?

Body:
you must set expand = 1

import tkinter.ttk as ttk
from tkinter import *

#entries is a list of lists containing the data I want to display

entries = []

for i in range(0,500):
    args = (i,'Name','Quiz 1', 'Quiz 2', 'MidSem')
    entries.append(args)

master = Tk()
tree = ttk.Treeview(master, columns=('Name', 'Quiz 1', 'Quiz 2', 'MidSem'))
tree.heading('#0', text='ID')
tree.heading('#1', text='Name')
tree.heading('#2', text='Quiz 1')
tree.heading('#3', text='Quiz 2 ')
tree.heading('#4', text='MidSem')
tree.column('#1', stretch=YES)
tree.column('#2', stretch=YES)
tree.column('#3', stretch=YES)
tree.column('#4', stretch=YES)
tree.column('#0', stretch=YES)
tree.pack(fill=BOTH,expand=1)

for entry in entries:
    tree.insert('', 'end', text=entry[0], values=(entry[1], entry[2], entry[3], entry[4]))


问:
JavaScript: Use forEach to see if array contains a specific number value
I have the code below. I am purposefully trying to use forEach in this instance.  </p>

```<code>function check(arr, el) {

  arr.forEach((element) => {

    console.log(element)

    if (element === el) {

       return true
    }
  })
}

check([1, 2, 3, 4, 5], 3)
</code>```

<p>I am expecting the code to return true because the el value of 3 is in the array.  But instead it returns undefined.  What am I doing wrong?  </p>

答:
forEach don't return anything ( means undefined ), you can use some

function check(arr, el) {
  return arr.some( element => element === el)
}

console.log(check([1, 2, 3, 4, 5], 3))```
</div>
</div>
</p>

<p>If you want to use <code>forEach</code> than use a variable to store value and than return later from function </p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function check(arr, el) {
  let found = false

  arr.forEach((element) => {
    if (element === el && !found){
      found = true
    }
  })
  return found
}

console.log(check([1, 2, 3, 4, 5], 3))</code>```

Body:
I have the code below. I am purposefully trying to use forEach in this instance.

function check(arr, el) {

  arr.forEach((element) => {

    console.log(element)

    if (element === el) {

       return true
    }
  })
}

check([1, 2, 3, 4, 5], 3)

I am expecting the code to return true because the el value of 3 is in the array.  But instead it returns undefined.  What am I doing wrong?

Body:
forEach don't return anything ( means undefined ), you can use some

function check(arr, el) {
  return arr.some( element => element === el)
}

console.log(check([1, 2, 3, 4, 5], 3))

If you want to use forEach than use a variable to store value and than return later from function

function check(arr, el) {
  let found = false

  arr.forEach((element) => {
    if (element === el && !found){
      found = true
    }
  })
  return found
}

console.log(check([1, 2, 3, 4, 5], 3))


问:
Specify constructor arguments for a Google test Fixture
With Google test I want to specify a Test fixture for use in different test cases.
The fixture shall allocate and deallocate objects of the class TheClass and its data management class TheClassData, where the data management class requires the name of a datafile.

For the different tests, the file name should vary.

I defined the following Fixture:

```<code>class TheClassTest : public ::testing::Test {
 protected:
  TheClassTest(std::string filename) : datafile(filename) {}
  virtual ~TheClassTest() {}
  virtual void SetUp() {
    data = new TheClassData(datafile);
    tc = new TheClass(data);
  }
  virtual void TearDown() {
    delete tc;
    delete data;
  }

  std::string datafile;
  TheClassData* data;
  TheClass* tc;
};
</code>```

Now, different tests should use the fixture with different file names.
Imagine this as setting up a test environment.

The question: How can I specify the filename from a test, i.e. how to call a non-default constructor of a fixture?

I found things like ::testing::TestWithParam<T> and TEST_P, which doesn't help, as I don't want to run one test with different values, but different tests with one fixture.

答:
If you overload the SetUp method as suggested here, and you want to ensure that you remember to use the overloaded SetUp, you can use an assertion in the TearDown method.

```<code>class my_fixture : public ::testing::Test
{
protected:
    bool SETUP_HIT_FLAG = false;

    void SetUp(double parameter)
    {
        ...
        SETUP_HIT_FLAG = true;
    }

    void TearDown() override
    {
        assert(SETUP_HIT_FLAG && "You forgot to call SetUp with your parameter!");
    }
};
</code>```

Body:
With Google test I want to specify a Test fixture for use in different test cases.
The fixture shall allocate and deallocate objects of the class TheClass and its data management class TheClassData, where the data management class requires the name of a datafile.

For the different tests, the file name should vary.

I defined the following Fixture:

class TheClassTest : public ::testing::Test {
 protected:
  TheClassTest(std::string filename) : datafile(filename) {}
  virtual ~TheClassTest() {}
  virtual void SetUp() {
    data = new TheClassData(datafile);
    tc = new TheClass(data);
  }
  virtual void TearDown() {
    delete tc;
    delete data;
  }

  std::string datafile;
  TheClassData* data;
  TheClass* tc;
};

Now, different tests should use the fixture with different file names.
Imagine this as setting up a test environment.

The question: How can I specify the filename from a test, i.e. how to call a non-default constructor of a fixture?

I found things like ::testing::TestWithParam<T> and TEST_P, which doesn't help, as I don't want to run one test with different values, but different tests with one fixture.

Body:
If you overload the SetUp method as suggested here, and you want to ensure that you remember to use the overloaded SetUp, you can use an assertion in the TearDown method.

class my_fixture : public ::testing::Test
{
protected:
    bool SETUP_HIT_FLAG = false;

    void SetUp(double parameter)
    {
        ...
        SETUP_HIT_FLAG = true;
    }

    void TearDown() override
    {
        assert(SETUP_HIT_FLAG && "You forgot to call SetUp with your parameter!");
    }
};


问:
has_rdoc is deprecated warning message after doing bundle update
Just finished updating my bundler and now I keep getting this messages:

NOTE: Gem::Specification#has_rdoc= is deprecated with no replacement. It will be removed on or after 2011-10-01.
Gem::Specification#has_rdoc= called from /Users/eumir/.rvm/gems/ruby-1.9.2-head@waftt/bundler/gems/watir-9e41fd458687/watir/watir.gemspec:43

I've googled for this eror and all it returns are pages to agile web development(looks like a tutorial but it has all the errors pasted in it...weird)

http://intertwingly.net/projects/AWDwR4/checkdepot-193-30/section-10.1.html

Anyway, is the only way to turn this off, going into each of my "outdated" gems' gemspecs and takign out that has_rdoc thing?

答:
You are seeing this error because the Gemspec for Watir calls has_rdoc, which is deprecated in the latest RubyGems API.

I'd imagine by the time has_rdoc is removed from the API, the Watir team will have removed this call.

This warning does not affect your app or your tests, so can be safely ignored for now.


问:
ADFS - Get user information
I need to authenticate myself with an AddIn (excel, word, powerpoint) in office 365.
The customer has a local ADFS that he would like to use to authenticate the user.
I would therefore like to authenticate myself on local ADFS, retrieve the token and user information and then use the AddIn and Azure Rights managment (RMS).
Authentication to ADFS must be done automatically, without entering login and password.</p>

答:
The usual way of doing this is to setup ADFS as a federated domain to Azure AD. Office 365 runs on Azure AD.

ADFS supports Windows Integrated Auth so a user logged into the domain joined PC will seamlessly log into ADFS.

Title: ADFS - Get user information


问:
Including local jar dependency with corresponding source jar in gradle
How can I include a local jar dependency and its corresponding sources jar (for my IDE, Intellij) in Gradle?

I have tried adding a flatDir to lib (a directory in the same parent directory as all the Gradle stuff) under repositories, where lib contains mylib-1.0.jar and mylib-1.0-sources.jar. I then put implementation name: "mylib-1.0" under dependencies. The jar with compiled classes was included, but not the sources.

I also tried creating a local maven repository. In this case, lib contained

```<code>lib/xxx/yyy/mylib/1.0/mylib-1.0.jar
</code>```

and

```<code>lib/xxx/yyy/mylib/1.0/mylib-1.0-sources.jar
</code>```

where xxx.yyy is the group ID. I added

```<code>maven {
    url uri("lib")
}
</code>```

under repositories and

```<code>implementation group: "xxx.yyy", name: "mylib", version: "1.0"
</code>```

under dependencies. Still did not work--neither jars were included this time.

I also tried adding a minimal POM in the same directory as both the jars, but that did not change anything.

Any idea as to where I could be going wrong?

Note: I am no expert at using Gradle or Maven.

Edit: Rationale: in case somebody suggests it, I am aware I can just include as a dependency the jar with the compiled class and "link" the sources jar to it in Intellij, but then every time I refresh gradle I have to re-link them.

答:
I provide below the following approaches.

Prior to gradle 5

```<code>dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
}
</code>```

Here libs is the directory which contains the list of jar files and it should be location inside your project base directory.

You can also use in the following manner if you have only one jar file. Here libs refer to the directory which contains only one jar file and libs is available in the project base directory.

```<code>dependencies {
    compile files('libs/your jar file name.jar')
}
</code>```

If you want to specify a list of jar files, you can use in the following manner.

```<code>dependencies {
compile files(‘libs/a.jar’,
‘libs/b.jar’,
‘libs/c.jar’
)
}
</code>```

In Gradle 5
You have to use in the follwong manner.

```<code>dependencies {
    externalLibs files('libs/a.jar', 'libs/b.jar')
}
</code>```

Body:
How can I include a local jar dependency and its corresponding sources jar (for my IDE, Intellij) in Gradle?

I have tried adding a flatDir to lib (a directory in the same parent directory as all the Gradle stuff) under repositories, where lib contains mylib-1.0.jar and mylib-1.0-sources.jar. I then put implementation name: "mylib-1.0" under dependencies. The jar with compiled classes was included, but not the sources.

I also tried creating a local maven repository. In this case, lib contained

lib/xxx/yyy/mylib/1.0/mylib-1.0.jar

and

lib/xxx/yyy/mylib/1.0/mylib-1.0-sources.jar

where xxx.yyy is the group ID. I added

maven {
    url uri("lib")
}

under repositories and

implementation group: "xxx.yyy", name: "mylib", version: "1.0"

under dependencies. Still did not work--neither jars were included this time.

I also tried adding a minimal POM in the same directory as both the jars, but that did not change anything.

Any idea as to where I could be going wrong?

Note: I am no expert at using Gradle or Maven.

Edit: Rationale: in case somebody suggests it, I am aware I can just include as a dependency the jar with the compiled class and "link" the sources jar to it in Intellij, but then every time I refresh gradle I have to re-link them.

Body:
I provide below the following approaches.

Prior to gradle 5

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
}

Here libs is the directory which contains the list of jar files and it should be location inside your project base directory.

You can also use in the following manner if you have only one jar file. Here libs refer to the directory which contains only one jar file and libs is available in the project base directory.

dependencies {
    compile files('libs/your jar file name.jar')
}

If you want to specify a list of jar files, you can use in the following manner.

dependencies {
compile files(‘libs/a.jar’,
‘libs/b.jar’,
‘libs/c.jar’
)
}

In Gradle 5
You have to use in the follwong manner.

dependencies {
    externalLibs files('libs/a.jar', 'libs/b.jar')
}


问:
IllegalArgumentException: width and height must be > 0 during zoomOut in Google MapView
I'm trying to zoom in on a Google MapView on step in the oncreateMethod of my Activity.
Everytime I try to zoom the map via the mapController I get an IllegalArgumentException:

```<code>04-15 10:16:51.012: ERROR/AndroidRuntime(528): java.lang.RuntimeException: Unable to start activity ComponentInfo{android.client/android.client.ui.showstores.StoreMap}: java.lang.IllegalArgumentException: width and height must be > 0
</code>```

This Exception is thrown if I call the zoomOut or zoomIn function of MapController. Sadly the zoomIn function I'm using does not take any arguments.

The onCreateMethod where I'm calling the zoom functions looks like this:

```<code>    mapView = (MapView) findViewById(R.id.map);
    mapView.setBuiltInZoomControls(true);
    MapController mapController = mapView.getController();
    mapController.zoomIn();
</code>```

I'm a little bit at loss here because I'm doing nothing special.

The whole stacktrace is:

```<code>04-15 10:16:51.012: ERROR/AndroidRuntime(528): java.lang.RuntimeException: Unable to start activity ComponentInfo{android.client/android.client.ui.showstores.StoreMap}: java.lang.IllegalArgumentException: width and height must be > 0
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2401)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2417)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at android.app.ActivityThread.access$2100(ActivityThread.java:116)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at android.os.Looper.loop(Looper.java:123)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at android.app.ActivityThread.main(ActivityThread.java:4203)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at java.lang.reflect.Method.invokeNative(Native Method)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at java.lang.reflect.Method.invoke(Method.java:521)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at dalvik.system.NativeStart.main(Native Method)
04-15 10:16:51.012: ERROR/AndroidRuntime(528): Caused by: java.lang.IllegalArgumentException: width and height must be > 0
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at android.graphics.Bitmap.nativeCreate(Native Method)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at android.graphics.Bitmap.createBitmap(Bitmap.java:468)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at com.google.android.maps.ZoomHelper.createSnapshot(ZoomHelper.java:305)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at com.google.android.maps.ZoomHelper.doZoom(ZoomHelper.java:137)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at com.google.android.maps.ZoomHelper.doZoom(ZoomHelper.java:126)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at com.google.android.maps.MapView.doZoom(MapView.java:1459)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at com.google.android.maps.MapView.doZoom(MapView.java:1468)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at com.google.android.maps.MapController.zoomIn(MapController.java:427)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at android.client.ui.showstores.StoreMap.onCreate(StoreMap.java:58)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     ... 11 more
</code>```

答: You might try to call the zoom methods in onWindowFocusChanged(boolean hasFocus) instead of onCreate or onResume.</p>

Body:
I'm trying to zoom in on a Google MapView on step in the oncreateMethod of my Activity.
Everytime I try to zoom the map via the mapController I get an IllegalArgumentException:

04-15 10:16:51.012: ERROR/AndroidRuntime(528): java.lang.RuntimeException: Unable to start activity ComponentInfo{android.client/android.client.ui.showstores.StoreMap}: java.lang.IllegalArgumentException: width and height must be > 0

This Exception is thrown if I call the zoomOut or zoomIn function of MapController. Sadly the zoomIn function I'm using does not take any arguments.

The onCreateMethod where I'm calling the zoom functions looks like this:

    mapView = (MapView) findViewById(R.id.map);
    mapView.setBuiltInZoomControls(true);
    MapController mapController = mapView.getController();
    mapController.zoomIn();

I'm a little bit at loss here because I'm doing nothing special.

The whole stacktrace is:

04-15 10:16:51.012: ERROR/AndroidRuntime(528): java.lang.RuntimeException: Unable to start activity ComponentInfo{android.client/android.client.ui.showstores.StoreMap}: java.lang.IllegalArgumentException: width and height must be > 0
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2401)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2417)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at android.app.ActivityThread.access$2100(ActivityThread.java:116)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1794)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at android.os.Looper.loop(Looper.java:123)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at android.app.ActivityThread.main(ActivityThread.java:4203)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at java.lang.reflect.Method.invokeNative(Native Method)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at java.lang.reflect.Method.invoke(Method.java:521)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:549)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at dalvik.system.NativeStart.main(Native Method)
04-15 10:16:51.012: ERROR/AndroidRuntime(528): Caused by: java.lang.IllegalArgumentException: width and height must be > 0
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at android.graphics.Bitmap.nativeCreate(Native Method)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at android.graphics.Bitmap.createBitmap(Bitmap.java:468)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at com.google.android.maps.ZoomHelper.createSnapshot(ZoomHelper.java:305)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at com.google.android.maps.ZoomHelper.doZoom(ZoomHelper.java:137)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at com.google.android.maps.ZoomHelper.doZoom(ZoomHelper.java:126)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at com.google.android.maps.MapView.doZoom(MapView.java:1459)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at com.google.android.maps.MapView.doZoom(MapView.java:1468)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at com.google.android.maps.MapController.zoomIn(MapController.java:427)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at android.client.ui.showstores.StoreMap.onCreate(StoreMap.java:58)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1123)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2364)
04-15 10:16:51.012: ERROR/AndroidRuntime(528):     ... 11 more


问:
How to Remove '\0' from a string in C#?
I would like to know how to remove '\0' from a string. This may be very simple but it's not for me since I'm a new C# developer.

I've this code:

```<code>public static void funcTest (string sSubject, string sBody)
{
    Try
      {
        MailMessage msg = new MailMessage(); // Set up e-mail message.
        msg.To = XMLConfigReader.Email;
        msg.From = XMLConfigReader.From_Email;
        msg.Subject = sSubject;
        msg.body="TestStrg.\r\nTest\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\r\n";
      }
    catch (Exception ex)
      {
        string sMessage = ex.Message;
        log.Error(sMessage, ex);
      }
}
</code>```

But what I want is:

```<code>msg.body="TestStrg.\r\nTest\r\n";
</code>```

So, is there a way to do this with a simple code?

答:
It may have a faster result if you use LINQ

```<code>str.TakeWhile(c => c != '\0');
</code>```

Linq has a better and faster performance.

Title: How to Remove '\0' from a string in C#?

Body:
I would like to know how to remove '\0' from a string. This may be very simple but it's not for me since I'm a new C# developer.

I've this code:

public static void funcTest (string sSubject, string sBody)
{
    Try
      {
        MailMessage msg = new MailMessage(); // Set up e-mail message.
        msg.To = XMLConfigReader.Email;
        msg.From = XMLConfigReader.From_Email;
        msg.Subject = sSubject;
        msg.body="TestStrg.\r\nTest\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\r\n";
      }
    catch (Exception ex)
      {
        string sMessage = ex.Message;
        log.Error(sMessage, ex);
      }
}

But what I want is:

msg.body="TestStrg.\r\nTest\r\n";

So, is there a way to do this with a simple code?

Body:
It may have a faster result if you use LINQ

str.TakeWhile(c => c != '\0');

Linq has a better and faster performance.


问:
What is the best way to use regex in a for loop while testing for data type?
What is the best way to use regex in a for loop while testing for data type?

For context, I'm looping over large unclean data sets with multiple data types and need to find extensions of strings, if they exist. Small changes to my code, like converting values to string costs me minutes.

I read through this question Python: How to use RegEx in an if statement? but couldn't find a way of testing for a match without first converting to a string.

Values:

```<code>vals = [444444, '555555-Z01']
pattern = re.compile('[-]*[A-Z]{1}[0-9]{2}$')
# new_vals = [444444, 555555]
</code>```

Slow method:  (2.4 µs ± 93.6 ns per loop)

```<code>new_vals = []
for v in vals:
    if type(v)==str:
        if pattern.search(v) is not None:
            new_v = pattern.findall(v)[0].replace('-','')
            new_vals.append(new_v)
    else:
        new_vals.append(v)
</code>```

Fast method: (1.84 µs ± 34.7 ns per loop)

```<code>f = lambda x: x if type(x)!=str else pattern.findall(x)[0].replace('-','')

new_vals = []
for v in vals:
    new_vals.append(f(v))
</code>```

Unsucessful Method:

```<code>new_vals = []
for v in vals:
    if ((type(v)==str) & (pattern.search(v) is not None)):
        new_vals.append(v)
</code>```

Error:

```<code>TypeError: expected string or bytes-like object
</code>```

答:
I tried to beat your attempts using try/except blocks but the exception handling seems to take too much time. So much for "better ask forgiveness than permission" ...

Your last attempt is the most promising, if you just change & by and, because & is the logical and and doesn't short circuit.

I'll go for this, in a list comprehension to speed it up slightly more, and drop the is not None test which is useless since if search succeeds, it returns a regex object, which is truthy:

```<code>new_vals = [v for v in vals if type(v)==str and pattern.search(v)]
</code>```

or with isinstance (same speed, tests subclasses of str too):

```<code>new_vals = [v for v in vals if isinstance(v,str) and pattern.search(v)]
</code>```

Body:
What is the best way to use regex in a for loop while testing for data type?

For context, I'm looping over large unclean data sets with multiple data types and need to find extensions of strings, if they exist. Small changes to my code, like converting values to string costs me minutes.

I read through this question Python: How to use RegEx in an if statement? but couldn't find a way of testing for a match without first converting to a string.

Values:

vals = [444444, '555555-Z01']
pattern = re.compile('[-]*[A-Z]{1}[0-9]{2}$')
# new_vals = [444444, 555555]

Slow method:  (2.4 µs ± 93.6 ns per loop)

new_vals = []
for v in vals:
    if type(v)==str:
        if pattern.search(v) is not None:
            new_v = pattern.findall(v)[0].replace('-','')
            new_vals.append(new_v)
    else:
        new_vals.append(v)

Fast method: (1.84 µs ± 34.7 ns per loop)

f = lambda x: x if type(x)!=str else pattern.findall(x)[0].replace('-','')

new_vals = []
for v in vals:
    new_vals.append(f(v))

Unsucessful Method:

new_vals = []
for v in vals:
    if ((type(v)==str) & (pattern.search(v) is not None)):
        new_vals.append(v)

Error:

TypeError: expected string or bytes-like object

Body:
I tried to beat your attempts using try/except blocks but the exception handling seems to take too much time. So much for "better ask forgiveness than permission" ...

Your last attempt is the most promising, if you just change & by and, because & is the logical and and doesn't short circuit.

I'll go for this, in a list comprehension to speed it up slightly more, and drop the is not None test which is useless since if search succeeds, it returns a regex object, which is truthy:

new_vals = [v for v in vals if type(v)==str and pattern.search(v)]

or with isinstance (same speed, tests subclasses of str too):

new_vals = [v for v in vals if isinstance(v,str) and pattern.search(v)]


问:
Changing year only in date in column with case statement
I have a table with end dates in different years and would like to change any year ending in '2004' to '4712'. The column is Date type and I keep getting an error

I have tried different codes and case statements but none of which worked

```<code>select
    case
        when h.EndDate like '2004%' then '4712%'
        else h.EndDate
    end as EndDate
from table h

1/31/2004
2/28/2004
3/31/2004
</code>```

and so on would be the only years changed to:

```<code>1/31/4712
2/28/4712
3/31/4712
</code>```

答:
Personally, I would use datefromparts():

```<code>select datefromparts(4712, month(h.enddate), day(h.enddate))
from h
where h.enddate >= '2014-01-01' and h.enddate < '2015-01-01';
</code>```

In an update, this looks like:

```<code>update h
    set enddate = datefromparts(4712, month(h.enddate), day(h.enddate))
    where h.enddate >= '2014-01-01' and h.enddate < '2015-01-01';
</code>```

Body:
I have a table with end dates in different years and would like to change any year ending in '2004' to '4712'. The column is Date type and I keep getting an error

I have tried different codes and case statements but none of which worked

select
    case
        when h.EndDate like '2004%' then '4712%'
        else h.EndDate
    end as EndDate
from table h

1/31/2004
2/28/2004
3/31/2004

and so on would be the only years changed to:

1/31/4712
2/28/4712
3/31/4712

Body:
Personally, I would use datefromparts():

select datefromparts(4712, month(h.enddate), day(h.enddate))
from h
where h.enddate >= '2014-01-01' and h.enddate < '2015-01-01';

In an update, this looks like:

update h
    set enddate = datefromparts(4712, month(h.enddate), day(h.enddate))
    where h.enddate >= '2014-01-01' and h.enddate < '2015-01-01';


问:
OpenGL Math - Projecting Screen space to World space coords
Time for a little bit of math for the end of the day..

I need to project 4 points of the window size:

<0,0> <1024,768>

Into a world space coordinates so it will form a quadrilateral shape that will later be used for terrain culling - without GluUnproject

For test only, I use mouse coordinates - and try to project them onto the world coords

答:
I had to make some adjustments to the answers provided here. But here's the code I ended up with (Note I'm using GLM, that could affect multiplication order). nearResult is the projected point on the near plane and farResult is the projected point on the far plane. I want to perform a ray cast to see what my mouse is hovering over so I convert them to a direction vector which will then originate from my camera's position.</p>

```<code>vec3 getRayFromScreenSpace(const vec2 & pos)
{
    mat4 invMat= inverse(m_glData.getPerspective()*m_glData.getView());
    vec4 near = vec4((pos.x - Constants::m_halfScreenWidth) / Constants::m_halfScreenWidth, -1*(pos.y - Constants::m_halfScreenHeight) / Constants::m_halfScreenHeight, -1, 1.0);
    vec4 far = vec4((pos.x - Constants::m_halfScreenWidth) / Constants::m_halfScreenWidth, -1*(pos.y - Constants::m_halfScreenHeight) / Constants::m_halfScreenHeight, 1, 1.0);
    vec4 nearResult = invMat*near;
    vec4 farResult = invMat*far;
    nearResult /= nearResult.w;
    farResult /= farResult.w;
    vec3 dir = vec3(farResult - nearResult );
    return normalize(dir);
}
</code>```

Body:
I had to make some adjustments to the answers provided here. But here's the code I ended up with (Note I'm using GLM, that could affect multiplication order). nearResult is the projected point on the near plane and farResult is the projected point on the far plane. I want to perform a ray cast to see what my mouse is hovering over so I convert them to a direction vector which will then originate from my camera's position.

vec3 getRayFromScreenSpace(const vec2 & pos)
{
    mat4 invMat= inverse(m_glData.getPerspective()*m_glData.getView());
    vec4 near = vec4((pos.x - Constants::m_halfScreenWidth) / Constants::m_halfScreenWidth, -1*(pos.y - Constants::m_halfScreenHeight) / Constants::m_halfScreenHeight, -1, 1.0);
    vec4 far = vec4((pos.x - Constants::m_halfScreenWidth) / Constants::m_halfScreenWidth, -1*(pos.y - Constants::m_halfScreenHeight) / Constants::m_halfScreenHeight, 1, 1.0);
    vec4 nearResult = invMat*near;
    vec4 farResult = invMat*far;
    nearResult /= nearResult.w;
    farResult /= farResult.w;
    vec3 dir = vec3(farResult - nearResult );
    return normalize(dir);
}


问:
Object reference for child class
```<code>namespace Test
{
    public class Program
    {
        static void Main(string[] args)
        {
            TestClass testC = new TestClass();
            testC.AssignRec(10);
            //testC.root - this is null
        }
    }

    public class TestClass
    {
        public Childclass root;
        public void Assign(int data)
        {
           AssigRec(this.root,data);
        }
        public void AssignRec(Childclass rootnode, int data)
        {
            if (rootnode == null)
            {
                rootnode = new Childclass(data);
            }
        }
    }

    public class Childclass
    {
        public int data;
        public Childclass(int data)
        {
            this.data = data;
        }
    }
}
</code>```

Updated the Child parameter name.
Assigning value for the subclass ChildClass inside the TestClass but after assigning and if I try to access the Childcalss value it is null. Not sure the reason.

答:
You have to assign "new ChildClass(data)" to current instance's root. For that you need to assign the new object to "this.root". Make a change in TestClass like below:</p>

```<code>    public class TestClass
    {
        public Childclass root;

        public void Assign(Childclass root, int data)
        {
            if (root == null)
            {
                //over here
                this.root = new Childclass(data);
            }
        }
    }
</code>```

Title: Object reference for child class

Body:
namespace Test
{
    public class Program
    {
        static void Main(string[] args)
        {
            TestClass testC = new TestClass();
            testC.AssignRec(10);
            //testC.root - this is null
        }
    }

    public class TestClass
    {
        public Childclass root;
        public void Assign(int data)
        {
           AssigRec(this.root,data);
        }
        public void AssignRec(Childclass rootnode, int data)
        {
            if (rootnode == null)
            {
                rootnode = new Childclass(data);
            }
        }
    }

    public class Childclass
    {
        public int data;
        public Childclass(int data)
        {
            this.data = data;
        }
    }
}

Updated the Child parameter name.
Assigning value for the subclass ChildClass inside the TestClass but after assigning and if I try to access the Childcalss value it is null. Not sure the reason.

Body:
You have to assign "new ChildClass(data)" to current instance's root. For that you need to assign the new object to "this.root". Make a change in TestClass like below:

    public class TestClass
    {
        public Childclass root;

        public void Assign(Childclass root, int data)
        {
            if (root == null)
            {
                //over here
                this.root = new Childclass(data);
            }
        }
    }


问:
I tried to send data to a api. On postman it works but it doesn't work with axios
I tried to send data with to a api on postman it works but it doesn't work with axios.I would like to know how to add headers to my code.</p>

```<code>var ticket = {
            road: e.state.road,
            amount: e.state.amount,
            day: e.state.day,
            mon: e.state.mon,
            pay:  e.state.pay,
            card:  e.state.card,
            cvc:  e.state.cvc,
            holdername: e.state.holdername,
            phone: e.state.phone,
            pin:  e.state.pin,
            nic: e.state.nic,
            email: e.state.email,

        }
          axios.post('http://localhost:8080/ticket', ticket).then(function(response) {
            e.setState({
              messageFromServer: response.data
            });
          });
</code>```

答:
Check the cors policy with your API, Postman doesn't check the cors.

Example: https://www.npmjs.com/package/cors for a NodeJS API

Body:
I tried to send data with to a api on postman it works but it doesn't work with axios.I would like to know how to add headers to my code.

var ticket = {
            road: e.state.road,
            amount: e.state.amount,
            day: e.state.day,
            mon: e.state.mon,
            pay:  e.state.pay,
            card:  e.state.card,
            cvc:  e.state.cvc,
            holdername: e.state.holdername,
            phone: e.state.phone,
            pin:  e.state.pin,
            nic: e.state.nic,
            email: e.state.email,

        }
          axios.post('http://localhost:8080/ticket', ticket).then(function(response) {
            e.setState({
              messageFromServer: response.data
            });
          });


答:
Just to use OP's context. since one has to use forEach.</p>

```<code>function check(arr, el) {

  let found = false;

  arr.forEach((element) => {
    console.log(element)
    if (element === el){
        found = true;
    }
  })

  return found;
}
</code>```

Title: JavaScript: Use forEach to see if array contains a specific number value

Body:
I have the code below. I am purposefully trying to use forEach in this instance.

function check(arr, el) {

  arr.forEach((element) => {

    console.log(element)

    if (element === el) {

       return true
    }
  })
}

check([1, 2, 3, 4, 5], 3)

I am expecting the code to return true because the el value of 3 is in the array.  But instead it returns undefined.  What am I doing wrong?

Body:
Just to use OP's context. since one has to use forEach.

function check(arr, el) {

  let found = false;

  arr.forEach((element) => {
    console.log(element)
    if (element === el){
        found = true;
    }
  })

  return found;
}


问:
How to fix collapsing navbar that doesn't collapse in Bootstrap
My collapsible navbar is not working on this basic site, and I am not sure why. I have tried to reorder the CDN scripts, copied and pasted directly from Boostrap's docs, and have double checked the code a few times. I'm sure it's a stupid mistake, but can anyone help me and point out what is happening here? The toggle button appears, but doesn't do anything when clicked. This is being used with a Django project.

<!doctype html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,
    initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
    <title>{% block title %}The title I'm using{% endblock title %}</title>

      Home
      <button class="navbar-toggler" type="button" data-toggle="collapse"
      data-target="navbarCollapse" aria-controls="navbarCollapse"
      aria-expanded="false" aria-label="Toggle navigation">

      </button>

        {% if user.is_authenticated %}
          <form class="form-inline ml-auto">

            Log out

            Change password
              Update user profile
              {{ user.username }}
          </form>
        {% else %}
          <form class="form-inline ml-auto">

            Log In

            Sign up
          </form>
        {% endif %}

        {% block content %}

        {% endblock content %}

```

答:
Incorrect attribute value in the toggle button:

```<code>data-target="navbarCollapse"
</code>```

It should look like this (include the pound symbol):

```<code>data-target="#navbarCollapse"
</code>```

Body:
Incorrect attribute value in the toggle button:

data-target="navbarCollapse"

It should look like this (include the pound symbol):

data-target="#navbarCollapse"


问:
How to change the value of a service variable from the component?
In my code, the user input should get passed to the deviceName string in my component (which it does), which in turn should get passed to the deviceIP string in my service.

I'm guessing the order in which I used the get / set methods is incorrect. Can anyone help me figure out what I've done wrong?

Here's my component:

```<code>@Component({
selector: 'app-section-computer-management',
templateUrl: './section-computer-management.component.html',
styleUrls: ['./section-computer-management.component.css'],
})

export class SectionComputerManagementComponent implements OnInit {
ping: number = 0;
public deviceName = 'cstorch-3420';

constructor(private _pingService: PingService) {
this._pingService.pingStream.subscribe(ping => {
  this.ping = ping; });
}

changeDIP(val){
  this._pingService.setDIP(this.deviceName);
}

showDIV() {
  alert(`GV ${this._pingService.getDIP}`);
}

ngOnInit() {}
}
</code>```

Here's my service:

```<code>@Injectable()
export class PingService {
pingStream: Subject<number> = new Subject<number>();
ping: number = 0;

deviceIp = "";
url = `http://${this.deviceIp}`;

setDIP(val: string) {
this.deviceIp = val;
}
getDIP(val: string) {
return this.deviceIp;
}

constructor(private _http: Http) {
interval(1000)
  .subscribe((data) => {
    let timeStart: number = performance.now();

    this._http.get(this.url)
      .subscribe((data) => {
        let timeEnd: number = performance.now();

        let ping: number = timeEnd - timeStart;
        this.ping = ping;
        this.pingStream.next(ping);
      });
  });
}
}
</code>```

Here's the template I'm using

```<code> <div class="section-container">
    <div class="cards">
        <div class="card-deck">
            <div class="card text mb-3 shadow card-theme">
                <div class="card-header card-header-theme text-center">
                    <h5>Please Enter A Device Name or IP Address</h5>
                </div>
                <div class="card-body">
                    <div ng-app="">
                        <p align="center"><input class ='form-control input-lg'
    style= "width:300px" [(ngModel)]="deviceName" type="text"> {{deviceName}}
    </p>

                    </div>
                </div>
            </div>
            <div class="card text-center mb-3 shadow card-theme">
                <div class="card-header card-header-theme">
                    <h5>Machine Ping</h5>
                </div>
                <div class="card-body">
                        {{ping | number:'1.0-0'}}ms
                </div>
            </div>
        </div>
            <div class="row-fluid cards">
                <div class="card shadow card-theme">
                    <div class="card-body">

                    </div>
                    <div class="col-sm-2">
                            <div class="card shadow card-theme">
                              <div class="card-body">
                                <h5 class="card-title">Special title treatment</h5>
                                <p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
                                <a href="#" class="btn btn-primary">Go
somewhere</a>
                              </div>
                </div>
            </div>
        </div>
    </div>
</code>```

and finally the module.ts file

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';
import { SidebarComponent } from './sidebar/sidebar.component';
import { SectionDashboardComponent } from './Sections/section-dashboard/section-dashboard.component';
import { SectionComputerManagementComponent } from './Sections/section-computer-management/section-computer-management.component';
import { SectionHelpdeskLinksComponent } from './Sections/section-helpdesk-links/section-helpdesk-links.component';
import { BarChartComponent } from './charts/bar-chart/bar-chart.component';
import { LineChartComponent } from './charts/line-chart/line-chart.component';
import { PieChartComponent } from './charts/pie-chart/pie-chart.component';
import { ChartsModule } from 'ng2-charts';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { freshServiceService } from './Services/freshservice.service';
import { PingService } from './Services/pingservice.service';
import { HttpModule } from '@angular/http';
import {FormsModule} from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent,
    NavbarComponent,
    SidebarComponent,
    SectionDashboardComponent,
    SectionComputerManagementComponent,
    SectionHelpdeskLinksComponent,
    BarChartComponent,
    LineChartComponent,
    PieChartComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ChartsModule,
    HttpClientModule,
    HttpModule,
    FormsModule,

  ],
  providers: [freshServiceService, PingService, HttpClient],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

答:
Using getter and setter from typescript:

in MyService.ts

```<code>_ping: number = 0;

public set ping(ping: number) {
  this._ping = ping;
}

public get ping() {
  return this._ping;
}
</code>```

in component.ts

```<code>constructor(private service: MyService) {}

changePing() {
  this.service.ping = 1;
  console.log(this.service.ping);
  // 1
}
</code>```

Body:
In my code, the user input should get passed to the deviceName string in my component (which it does), which in turn should get passed to the deviceIP string in my service.

I'm guessing the order in which I used the get / set methods is incorrect. Can anyone help me figure out what I've done wrong?

Here's my component:

@Component({
selector: 'app-section-computer-management',
templateUrl: './section-computer-management.component.html',
styleUrls: ['./section-computer-management.component.css'],
})

export class SectionComputerManagementComponent implements OnInit {
ping: number = 0;
public deviceName = 'cstorch-3420';

constructor(private _pingService: PingService) {
this._pingService.pingStream.subscribe(ping => {
  this.ping = ping; });
}

changeDIP(val){
  this._pingService.setDIP(this.deviceName);
}

showDIV() {
  alert(`GV ${this._pingService.getDIP}`);
}

ngOnInit() {}
}

Here's my service:

@Injectable()
export class PingService {
pingStream: Subject<number> = new Subject<number>();
ping: number = 0;

deviceIp = "";
url = `http://${this.deviceIp}`;

setDIP(val: string) {
this.deviceIp = val;
}
getDIP(val: string) {
return this.deviceIp;
}

constructor(private _http: Http) {
interval(1000)
  .subscribe((data) => {
    let timeStart: number = performance.now();

    this._http.get(this.url)
      .subscribe((data) => {
        let timeEnd: number = performance.now();

        let ping: number = timeEnd - timeStart;
        this.ping = ping;
        this.pingStream.next(ping);
      });
  });
}
}

Here's the template I'm using

Please Enter A Device Name or IP Address

<input class ='form-control input-lg'
    style= "width:300px" [(ngModel)]="deviceName" type="text"> {{deviceName}}

Machine Ping

                        {{ping | number:'1.0-0'}}ms

Special title treatment

With supporting text below as a natural lead-in to additional content.

                                Go
somewhere

and finally the module.ts file

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';
import { SidebarComponent } from './sidebar/sidebar.component';
import { SectionDashboardComponent } from './Sections/section-dashboard/section-dashboard.component';
import { SectionComputerManagementComponent } from './Sections/section-computer-management/section-computer-management.component';
import { SectionHelpdeskLinksComponent } from './Sections/section-helpdesk-links/section-helpdesk-links.component';
import { BarChartComponent } from './charts/bar-chart/bar-chart.component';
import { LineChartComponent } from './charts/line-chart/line-chart.component';
import { PieChartComponent } from './charts/pie-chart/pie-chart.component';
import { ChartsModule } from 'ng2-charts';
import { HttpClientModule, HttpClient } from '@angular/common/http';
import { freshServiceService } from './Services/freshservice.service';
import { PingService } from './Services/pingservice.service';
import { HttpModule } from '@angular/http';
import {FormsModule} from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent,
    NavbarComponent,
    SidebarComponent,
    SectionDashboardComponent,
    SectionComputerManagementComponent,
    SectionHelpdeskLinksComponent,
    BarChartComponent,
    LineChartComponent,
    PieChartComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ChartsModule,
    HttpClientModule,
    HttpModule,
    FormsModule,

  ],
  providers: [freshServiceService, PingService, HttpClient],
  bootstrap: [AppComponent]
})
export class AppModule { }

Body:
Using getter and setter from typescript:

in MyService.ts

_ping: number = 0;

public set ping(ping: number) {
  this._ping = ping;
}

public get ping() {
  return this._ping;
}

in component.ts

constructor(private service: MyService) {}

changePing() {
  this.service.ping = 1;
  console.log(this.service.ping);
  // 1
}


问:
DAX, PowerBI: Calculated column with annual max value from other calculated column

I have a calculated table with dates from calendar table, [Rok] is Year([Data]), KB... columns are just values for this and last 3 years for that day, Avg KB t-3 is calculated column with average value from last 3 years.

I need to add a calculated column with MAX of [Avg KB t-3] for each Rok.

It sounds very easy, yet I've tried many different approaches and failed.

Please enlighten me with your ideas, for I have lost :)

答:
You can use the following:</p>

```<code>MaxAverage = CALCULATE(MAX('YourTable'[Avg KB t-3]);FILTER('YourTable';'YourTable'[Rok] = EARLIER('YourTable'[Rok])))
</code>```

Body:
You can use the following:

MaxAverage = CALCULATE(MAX('YourTable'[Avg KB t-3]);FILTER('YourTable';'YourTable'[Rok] = EARLIER('YourTable'[Rok])))


问:
call to php file via ajax not working
This seems like a relatively simple question, and I am pretty new to using ajax, but I saw a post about being able to call a PHP script when an OnClick event has been triggered. I am trying to destroy a session upon a user clicking the "Log Out" link, so I want to call the logout.php file when the OnClick event has occurred. My problem is that nothing happens when the link is clicked.

Here's my code:

```<code>$(document).ready(function() {

// Expand Panel
$("#open").click(function(){
    //when the user clicks the logout button
    $.ajax({
        url: "logout.php"
    )};
});
});

<div class="tab">
    <ul class="login">
        <li class="left"> </li>
        <li><?php if(isset($_SESSION['username'])){echo $_SESSION['username'];}else{echo 'Hello Guest!';}?></li>
        <li class="sep">|</li>
        <li id="toggle">
            <a id="open" class="open" href="#">Log Out</a>
        </li>
        <li class="right"> </li>
    </ul>
</div> <!-- / top -->
</code>```

答:
Try doing this:

```<code>$(document).ready(function() {
  alert('loaded!')
  // Expand Panel
  $("#open").click(function(){
    //when the user clicks the logout button
    $.ajax({
      url: "logout.php"
    )};
    alert('clicked!')
  });
});
</code>```

If this displays a popup saying clicked! then the event is being triggered. Tell me what happens so we can narrow it down to the $.ajax failing or the click event not being triggered.

If you are using firebug then you can go to the console panel and inspect XmlHttpRequests to closely look at any responses coming back from the remote script, if you have sent any back from the script that is.

Title: call to php file via ajax not working

Body:
This seems like a relatively simple question, and I am pretty new to using ajax, but I saw a post about being able to call a PHP script when an OnClick event has been triggered. I am trying to destroy a session upon a user clicking the "Log Out" link, so I want to call the logout.php file when the OnClick event has occurred. My problem is that nothing happens when the link is clicked.

Here's my code:

$(document).ready(function() {

// Expand Panel
$("#open").click(function(){
    //when the user clicks the logout button
    $.ajax({
        url: "logout.php"
    )};
});
});

<?php if(isset($_SESSION['username'])){echo $_SESSION['username'];}else{echo 'Hello Guest!';}?>

|

            Log Out

Body:
Try doing this:

$(document).ready(function() {
  alert('loaded!')
  // Expand Panel
  $("#open").click(function(){
    //when the user clicks the logout button
    $.ajax({
      url: "logout.php"
    )};
    alert('clicked!')
  });
});

If this displays a popup saying clicked! then the event is being triggered. Tell me what happens so we can narrow it down to the $.ajax failing or the click event not being triggered.

If you are using firebug then you can go to the console panel and inspect XmlHttpRequests to closely look at any responses coming back from the remote script, if you have sent any back from the script that is.


问:
how to extract a number in between strings using regex
I have the following text

Stat indicator : 01245 Values loaded

Some irrelevant data

Stat indicator : 13452 Values loaded

My output should be giving me numbers 01245, 13452

Heres what I have tried

```<code>with open('test.txt') as fd:
    data = fd.read()
val_to_pattern = {'stat': r'Stat indicator : .{5}\n'}
val_dict = {}
for key, patt in val_to_pattern.items():
    val_dict[key] = re.findall(patt, data)
</code>```

答:
You can used regex \d, and if you know the size of your number you can use {size} with it.

\d{3} Returns a match where the string contains 3 digits (numbers from
  0-9)

\d{3,5} Returns a match where the string contains 3 to 5 digits
  (numbers from 0-9)

So you can used r'\d{3,5}' as regex pattern

```<code>import re

with open('test.txt') as fd:
    data = fd.read()
val_to_pattern = {'stat': r'\d{5}'}
val_dict = {}
for key, patt in val_to_pattern.items():
    re_find = re.findall(patt, data)
    val_dict[key] = re.findall(patt, data)
</code>```

Body:
I have the following text

Stat indicator : 01245 Values loaded

Some irrelevant data

Stat indicator : 13452 Values loaded

My output should be giving me numbers 01245, 13452

Heres what I have tried

with open('test.txt') as fd:
    data = fd.read()
val_to_pattern = {'stat': r'Stat indicator : .{5}\n'}
val_dict = {}
for key, patt in val_to_pattern.items():
    val_dict[key] = re.findall(patt, data)

Body:
You can used regex \d, and if you know the size of your number you can use {size} with it.

\d{3} Returns a match where the string contains 3 digits (numbers from
  0-9)

\d{3,5} Returns a match where the string contains 3 to 5 digits
  (numbers from 0-9)

So you can used r'\d{3,5}' as regex pattern

import re

with open('test.txt') as fd:
    data = fd.read()
val_to_pattern = {'stat': r'\d{5}'}
val_dict = {}
for key, patt in val_to_pattern.items():
    re_find = re.findall(patt, data)
    val_dict[key] = re.findall(patt, data)