问:
How to align item in middle of navbar?
There is 6 items in navbar:

first 3 items should be aligned as flex-start - on beginning of navbar.

Then Logo should be in center of navbar

And on the end -> flex-end should come 2 icons

Here is screenshot of navbar current condition:

Problem: is position of Logo - am using margin-left: '27%'. And on different screen size logo is not aligned well.

I would like to align some how that logo trough flex, is there a way to do that with flex?

Check the code:

HTML/jsx:

```<code> <div className="container">
  <header className="header">
    <nav className="user-nav">
      <div className="user-nav-item">
        <Link href="/">
          <a className="user-nav-item-link">Overview</a>
        </Link>
      </div>
      <div className="user-nav-item">
        <Link href="/search">
          <a className="user-nav-item-link">Search</a>
        </Link>
      </div>
      <div className="user-nav-item">
        <Link href="/feed">
          <a className="user-nav-item-link">Feed</a>
        </Link>
      </div>
      <h3 className="logo">Logo</h3>
    </nav>

    <div className="user-nav-icon">
      <div className="user-nav-icon-box">
        <img src={bellIcon} alt="notify icon" />
      </div>
      <div className="user-nav-icon-box">
        <img src={settingsIcon} alt="settings icon" />
      </div>
    </div>
  </header>
</div>
</code>```

CSS:

```<code>.container {
  max-width: 100vw;
  display: flex;
  flex-direction: column;

.header {
  display: flex;
  align-items: center;
  height: 5rem;
  color: #fff;
  background-color: black;

  .user-nav {
    width: 100%;
    display: flex;
    align-items: center;

    &-item {
      width: 5.5rem;
      padding: 1.5rem;
      cursor: pointer;
    }

    &-item-link {
      text-decoration: none;
      color: white;
    }

    .logo {
      margin-left: 27%;
    }

    &-icon {
      display: flex;
      align-items: center;
      background-color: white;
      color: red;
      margin-right: 3rem;

      & > * {
        padding: 0 0.8rem;
        cursor: pointer;
      }

      &-icon-notification {
        color: red;
      }
    }
  }
}

}
</code>```

答:
Here is an answer using display: flex; Flexbox is best & elegant to align items to mid of the page without cheesy computations by Margin, Transform,...</p>

```<code><html>
  <head>
    <style>
      *, .container {
        width: 100%;
        top: 0;
        left: 0;
        padding: 0;
        margin: 0;
        color: ivory;
        font-family: Arial,"Helvetica Neue",Helvetica,sans-serif;
        font-size: 13px;
      }

      .header {
        display: flex;
        align-items: center;
        padding: 10px;
        background-color: gray;
      }

      .user-nav {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 30%;
      }

      .user-nav-item {
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .logo {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 40%;
      }

      .user-nav-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 30%;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <header class="header">
        <nav class="user-nav">
          <div class="user-nav-item">
            <Link href="/">
              <a class="user-nav-item-link">Overview</a>
            </Link>
          </div>
          <div class="user-nav-item">
            <Link href="/search">
              <a class="user-nav-item-link">Search</a>
            </Link>
          </div>
          <div class="user-nav-item">
            <Link href="/feed">
              <a class="user-nav-item-link">Feed</a>
            </Link>
          </div>
        </nav>
        <h3 class="logo">Logoooooooooooooooooooooo</h3>
        <div class="user-nav-icon">
          <div class="user-nav-icon-box">
            <img src={bellIcon} alt="notify icon" />
          </div>
          <div class="user-nav-icon-box">
            <img src={settingsIcon} alt="settings icon" />
          </div>
        </div>
      </header>
    </div>
  </body>
</html>
</code>```

Title: How to align item in middle of navbar?

Body:
There is 6 items in navbar:

first 3 items should be aligned as flex-start - on beginning of navbar.

Then Logo should be in center of navbar

And on the end -> flex-end should come 2 icons

Here is screenshot of navbar current condition:

Problem: is position of Logo - am using margin-left: '27%'. And on different screen size logo is not aligned well.

I would like to align some how that logo trough flex, is there a way to do that with flex?

Check the code:

HTML/jsx:

        <Link href="/">
          Overview
        </Link>

        <Link href="/search">
          Search
        </Link>

        <Link href="/feed">
          Feed
        </Link>

Logo

CSS:

.container {
  max-width: 100vw;
  display: flex;
  flex-direction: column;

.header {
  display: flex;
  align-items: center;
  height: 5rem;
  color: #fff;
  background-color: black;

  .user-nav {
    width: 100%;
    display: flex;
    align-items: center;

    &-item {
      width: 5.5rem;
      padding: 1.5rem;
      cursor: pointer;
    }

    &-item-link {
      text-decoration: none;
      color: white;
    }

    .logo {
      margin-left: 27%;
    }

    &-icon {
      display: flex;
      align-items: center;
      background-color: white;
      color: red;
      margin-right: 3rem;

      & > * {
        padding: 0 0.8rem;
        cursor: pointer;
      }

      &-icon-notification {
        color: red;
      }
    }
  }
}

}

Body:
Here is an answer using display: flex; Flexbox is best & elegant to align items to mid of the page without cheesy computations by Margin, Transform,...

<html>
  <head>
    <style>
      *, .container {
        width: 100%;
        top: 0;
        left: 0;
        padding: 0;
        margin: 0;
        color: ivory;
        font-family: Arial,"Helvetica Neue",Helvetica,sans-serif;
        font-size: 13px;
      }

      .header {
        display: flex;
        align-items: center;
        padding: 10px;
        background-color: gray;
      }

      .user-nav {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 30%;
      }

      .user-nav-item {
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .logo {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 40%;
      }

      .user-nav-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 30%;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <header class="header">
        <nav class="user-nav">
          <div class="user-nav-item">
            <Link href="/">
              <a class="user-nav-item-link">Overview</a>
            </Link>
          </div>
          <div class="user-nav-item">
            <Link href="/search">
              <a class="user-nav-item-link">Search</a>
            </Link>
          </div>
          <div class="user-nav-item">
            <Link href="/feed">
              <a class="user-nav-item-link">Feed</a>
            </Link>
          </div>
        </nav>
        <h3 class="logo">Logoooooooooooooooooooooo</h3>
        <div class="user-nav-icon">
          <div class="user-nav-icon-box">
            <img src={bellIcon} alt="notify icon" />
          </div>
          <div class="user-nav-icon-box">
            <img src={settingsIcon} alt="settings icon" />
          </div>
        </div>
      </header>
    </div>
  </body>
</html>


来源: stackexchange

问:
Laravel whereDate() with local timezone
So, basically, I want to build this SQL; notice the "localtime":

```<code>select [columns redacted] from "data"
where
  strftime('%Y-%m-%d', "time", "localtime") = cast("2019-05-27" as text)
</code>```

So far, I've tried:

```<code>$data = data::select([columns redacted])
    ->whereDate('time', $date)
    ->get();
</code>```

And, of course, it generates this:

```<code>select [columns redacted] from "data" where strftime('%Y-%m-%d', "time") = cast("2019-05-27" as text)
</code>```

And I don't know how to pass the "localtime" to whereDate(). Any help would be appreciated.

答:
You can use whereRaw</p>

```<code>->whereRaw('strftime("%Y-%m-%d", time, "localtime") = ?', ['2019-05-27'])
</code>```

ContentLicense: CC BY-SA 4.0

Title: Laravel whereDate() with local timezone

Body:
So, basically, I want to build this SQL; notice the "localtime":

select [columns redacted] from "data"
where
  strftime('%Y-%m-%d', "time", "localtime") = cast("2019-05-27" as text)

So far, I've tried:

$data = data::select([columns redacted])
    ->whereDate('time', $date)
    ->get();

And, of course, it generates this:

select [columns redacted] from "data" where strftime('%Y-%m-%d', "time") = cast("2019-05-27" as text)

And I don't know how to pass the "localtime" to whereDate(). Any help would be appreciated.

Body:
You can use whereRaw

->whereRaw('strftime("%Y-%m-%d", time, "localtime") = ?', ['2019-05-27'])


问:
Select is not valid at this position for this server version, expecting: '(', WITH
I get a syntax error with my SQL statement and I don't know where it is wrong. I'll greatly appreciate it if anyone here can shed some light. Thanks in advance!

```<code>SELECT YEAR(co.CO_APPLIED_DT) as SCO_YEAR
      ,MONTH(co.CO_APPLIED_DT) as SCO_MONTH_ID
      ,co.CO_OWNER_ACCNID as SCO_APPL_ACCNID
      ,co.CO_APPROVER_ACCNID as SCO_APPR_ACCNID
      ,co.CO_ISSUE_CTRY_CD as SCO_ISSUE_CTRY_CD
      ,co.CO_FINALDEST_CTRY_CD as SCO_DEST_CTRY_CD
      ,'99999999' AS SCO_HS_CHAP_CD
      ,SUM(CASE
             WHEN co.CO_STATUS IN ('A','P', 'T', 'E', 'C', 'F', 'L') THEN 1
             ELSE 0
           END) AS SCO_APPROVED_CT
      ,SUM(CASE
             WHEN co.CO_STATUS = 'U' THEN 1
             ELSE 0
           END) AS SCO_CANCELLED_CT
      ,SUM(CASE
             WHEN co.CO_STATUS = 'R' THEN 1
             ELSE 0
           END) AS SCO_REJECTED_CT
      ,0 AS SCO_HS_CHAP_CT
  FROM TDocCo co
 WHERE co.CO_STATUS NOT IN ('N', 'D')
   AND co.CO_APPLIED_DT <= :date
   AND YEAR(co.CO_APPLIED_DT) = :year
   AND MONTH(co.CO_APPLID_DT) = :month
 GROUP BY co.CO_APPROVER_ACCNID
         ,co.CO_OWNER_ACCNID
         ,co.CO_ISSUE_CTRY_CD
         ,co.CO_FINALDEST_CTRY_CD
         ,YEAR(co.CO_APPLIED_DT)
         ,MONTH(co.CO_APPLIED_DT);
</code>```

I'm getting the error message as shown above.

答:
These are my 2 cents:
In my local Db I wrote your query, only changing parameters  :date :year and :month  with today values.  It seems right!</p>

```<code> SELECT
    getDate() as CO_APPLIED_DT,
     23 as CO_OWNER_ACCNID,
     42 as CO_APPROVER_ACCNID,
    'England' as CO_ISSUE_CTRY_CD,
    'Poland' as CO_FINALDEST_CTRY_CD,
    'A' as CO_STATUS
   INTO TDocCo

SELECT  YEAR(co.CO_APPLIED_DT) as SCO_YEAR,
    MONTH(co.CO_APPLIED_DT) as SCO_MONTH_ID,
    co.CO_OWNER_ACCNID as SCO_APPL_ACCNID,
    co.CO_APPROVER_ACCNID as SCO_APPR_ACCNID,
    co.CO_ISSUE_CTRY_CD as SCO_ISSUE_CTRY_CD,
    co.CO_FINALDEST_CTRY_CD as SCO_DEST_CTRY_CD,
    '99999999' AS SCO_HS_CHAP_CD,
    SUM(CASE WHEN co.CO_STATUS IN ('A','P', 'T', 'E', 'C', 'F', 'L') THEN 1 ELSE 0 END) AS SCO_APPROVED_CT,
    SUM(CASE WHEN co.CO_STATUS = 'U' THEN 1 ELSE 0 END) AS SCO_CANCELLED_CT,
    SUM(CASE WHEN co.CO_STATUS = 'R' THEN 1 ELSE 0 END) AS SCO_REJECTED_CT,
    0 AS SCO_HS_CHAP_CT
  FROM TDocCo co
  WHERE co.CO_STATUS NOT IN ('N', 'D')
     AND co.CO_APPLIED_DT <=   getDate()                -- modified
     AND YEAR(co.CO_APPLIED_DT) =  year (getDate())     -- modified
     AND MONTH(co.CO_APPLIED_DT) =  month (getDate())   -- modified
  GROUP BY co.CO_APPROVER_ACCNID, co.CO_OWNER_ACCNID, co.CO_ISSUE_CTRY_CD, co.CO_FINALDEST_CTRY_CD, YEAR(co.CO_APPLIED_DT), MONTH(co.CO_APPLIED_DT);

 DROP TABLE  TDocCo
</code>```

Body:
I get a syntax error with my SQL statement and I don't know where it is wrong. I'll greatly appreciate it if anyone here can shed some light. Thanks in advance!

SELECT YEAR(co.CO_APPLIED_DT) as SCO_YEAR
      ,MONTH(co.CO_APPLIED_DT) as SCO_MONTH_ID
      ,co.CO_OWNER_ACCNID as SCO_APPL_ACCNID
      ,co.CO_APPROVER_ACCNID as SCO_APPR_ACCNID
      ,co.CO_ISSUE_CTRY_CD as SCO_ISSUE_CTRY_CD
      ,co.CO_FINALDEST_CTRY_CD as SCO_DEST_CTRY_CD
      ,'99999999' AS SCO_HS_CHAP_CD
      ,SUM(CASE
             WHEN co.CO_STATUS IN ('A','P', 'T', 'E', 'C', 'F', 'L') THEN 1
             ELSE 0
           END) AS SCO_APPROVED_CT
      ,SUM(CASE
             WHEN co.CO_STATUS = 'U' THEN 1
             ELSE 0
           END) AS SCO_CANCELLED_CT
      ,SUM(CASE
             WHEN co.CO_STATUS = 'R' THEN 1
             ELSE 0
           END) AS SCO_REJECTED_CT
      ,0 AS SCO_HS_CHAP_CT
  FROM TDocCo co
 WHERE co.CO_STATUS NOT IN ('N', 'D')
   AND co.CO_APPLIED_DT <= :date
   AND YEAR(co.CO_APPLIED_DT) = :year
   AND MONTH(co.CO_APPLID_DT) = :month
 GROUP BY co.CO_APPROVER_ACCNID
         ,co.CO_OWNER_ACCNID
         ,co.CO_ISSUE_CTRY_CD
         ,co.CO_FINALDEST_CTRY_CD
         ,YEAR(co.CO_APPLIED_DT)
         ,MONTH(co.CO_APPLIED_DT);

I'm getting the error message as shown above.

Body:
These are my 2 cents:
In my local Db I wrote your query, only changing parameters  :date :year and :month  with today values.  It seems right!

 SELECT
    getDate() as CO_APPLIED_DT,
     23 as CO_OWNER_ACCNID,
     42 as CO_APPROVER_ACCNID,
    'England' as CO_ISSUE_CTRY_CD,
    'Poland' as CO_FINALDEST_CTRY_CD,
    'A' as CO_STATUS
   INTO TDocCo

SELECT  YEAR(co.CO_APPLIED_DT) as SCO_YEAR,
    MONTH(co.CO_APPLIED_DT) as SCO_MONTH_ID,
    co.CO_OWNER_ACCNID as SCO_APPL_ACCNID,
    co.CO_APPROVER_ACCNID as SCO_APPR_ACCNID,
    co.CO_ISSUE_CTRY_CD as SCO_ISSUE_CTRY_CD,
    co.CO_FINALDEST_CTRY_CD as SCO_DEST_CTRY_CD,
    '99999999' AS SCO_HS_CHAP_CD,
    SUM(CASE WHEN co.CO_STATUS IN ('A','P', 'T', 'E', 'C', 'F', 'L') THEN 1 ELSE 0 END) AS SCO_APPROVED_CT,
    SUM(CASE WHEN co.CO_STATUS = 'U' THEN 1 ELSE 0 END) AS SCO_CANCELLED_CT,
    SUM(CASE WHEN co.CO_STATUS = 'R' THEN 1 ELSE 0 END) AS SCO_REJECTED_CT,
    0 AS SCO_HS_CHAP_CT
  FROM TDocCo co
  WHERE co.CO_STATUS NOT IN ('N', 'D')
     AND co.CO_APPLIED_DT <=   getDate()                -- modified
     AND YEAR(co.CO_APPLIED_DT) =  year (getDate())     -- modified
     AND MONTH(co.CO_APPLIED_DT) =  month (getDate())   -- modified
  GROUP BY co.CO_APPROVER_ACCNID, co.CO_OWNER_ACCNID, co.CO_ISSUE_CTRY_CD, co.CO_FINALDEST_CTRY_CD, YEAR(co.CO_APPLIED_DT), MONTH(co.CO_APPLIED_DT);

 DROP TABLE  TDocCo


问:
Is it ok to unit-test an abstract class by instantiating it as a mock object?
It has come to my attention that you can unit-test an abstract class by instantiating it as a mock object. Thereby you mock the abstract properties and methods, while being able to test the implemented ones.

However, I am accustomed to distinguish between the class to test and the injected dependencies to mock/stub. So, in this early stage of my new enlightenment I wonder if there are any pitfalls to this way of testing?? Any thoughts on this?

Regards,
Morten

答:
An abstract class, to be of any value, should have concrete subclasses which can be instantiated. So unit test those, and via them implicitly the base class.

If it has no concrete subclasses, I can't think of any reason why it should exist (as an abstract class, that is).

In general, I prefer to use mocking only to set up the environment of the class to be tested, not to instantiate the class itself. This distinction - to me - keeps the test cases clearer, and ensures that I always test the real functionality of the class.

Of course, I can think of cases (with legacy code) when the main issue is to be able to write unit tests somehow, anyhow, to enable refactoring (as discussed in Working Effectively with Legacy Code). As a temporary solution in such cases, (almost) anything goes. But once the unit tests are working, the class should be refactored properly asap to make it clean and testable (and its unit tests too, to make them maintainable).

ContentLicense: CC BY-SA 3.0


问:
How can a List of INDArrays be stored in a file
I am working on an reinforcement-learning project and have a List<INDArray> which holds a list of states of the world and a second List<INDArray>which holds action-prediction and reward values with the index corresponding to the states of the first List

I want to store these data for later training on the hard-drive, how can I achieve this?

Lets sax for example we have:

```<code>List<INDArray> stateList = new ArrayList<>();
stateList.add(Nd4j.valueArrayOf(new int[]{3,3,3}, 5));
stateList.add(Nd4j.valueArrayOf(new int[]{3,3,3}, 6));

List<INDArray> valueList = new ArrayList<>();
valueList.add(Nd4j.create(new float[]{1, 2}));
valueList.add(Nd4j.create(new float[]{3, 4}));
</code>```

答:
you have to preparefile content and then simply write into file.</p>

```<code>        String fileContent = "";
        for (INDArray arr : valueList) {
            str +=arr.getValue()+"/n";//arr.getValue() anything which u want to add
        }

        FileWriter fileWriter = new FileWriter("c:/temp/samplefile.txt");
        fileWriter.write(fileContent);
        fileWriter.close();
</code>```

Body:
I am working on an reinforcement-learning project and have a List<INDArray> which holds a list of states of the world and a second List<INDArray>which holds action-prediction and reward values with the index corresponding to the states of the first List

I want to store these data for later training on the hard-drive, how can I achieve this?

Lets sax for example we have:

List<INDArray> stateList = new ArrayList<>();
stateList.add(Nd4j.valueArrayOf(new int[]{3,3,3}, 5));
stateList.add(Nd4j.valueArrayOf(new int[]{3,3,3}, 6));

List<INDArray> valueList = new ArrayList<>();
valueList.add(Nd4j.create(new float[]{1, 2}));
valueList.add(Nd4j.create(new float[]{3, 4}));

Body:
you have to preparefile content and then simply write into file.

        String fileContent = "";
        for (INDArray arr : valueList) {
            str +=arr.getValue()+"/n";//arr.getValue() anything which u want to add
        }

        FileWriter fileWriter = new FileWriter("c:/temp/samplefile.txt");
        fileWriter.write(fileContent);
        fileWriter.close();


问:
Retrieving the last element of a list in Panda Dataframe column
I have this csv file example: (read this as item AAA costs 1000 and item AAA(1) costs 2000)

```<code>ColumnName
AAA (1000)
AAA (1) (2000)
</code>```

I would like to create a pandas dataframe column of all numbers

ie

```<code>Column_cost
1000
2000
</code>```

I tried to split this by '(' which returns something like the following (because the second item has '(' in the name:

```<code>Result 1
Col_1 Col_2 Col_3

AAA 1000) None

AAA   1)  2000)
</code>```

so the numbers are not in the same column

I then tried creating a columns of lists which gives

```<code>Result 2

ColumnName2

[AAA,1000)]

[AAA,1),2000)]
</code>```

but again, I don't know how to create a column that uses the last element of each list.

I can get it for a particular index, but not for the whole column

```<code>x = df['ColumnName'].str.split('(',expand=True) gives Result 1 above

x = df['ColumnName'].str.split('(') gives Result 2 above
</code>```

From Result 2, I did the following to get the desired result for one particular cell, but I don't know how to do it for the whole column (I can do this for a small dataset, but not for a large one)

retrieves the list of a particular index, gets the last element of the list, splits it by spaces, and then retrieves the new element of the split list

```<code>x[0][-1].split()[0]
x[1][-1].split()[0]
</code>```

答:
You could use str.extract to match the digits inside the parenthesis, and add '$' so it matches only at the end of the string:

```<code>df.assign(Column_cost = df.ColumnName.str.extract(r'\((\d+)\)$'))

       ColunmName    Column_cost
0      AAA (1000)        1000
1  AAA (1) (2000)        2000
</code>```

Body:
I have this csv file example: (read this as item AAA costs 1000 and item AAA(1) costs 2000)

ColumnName
AAA (1000)
AAA (1) (2000)

I would like to create a pandas dataframe column of all numbers

ie

Column_cost
1000
2000

I tried to split this by '(' which returns something like the following (because the second item has '(' in the name:

Result 1
Col_1 Col_2 Col_3

AAA 1000) None

AAA   1)  2000)

so the numbers are not in the same column

I then tried creating a columns of lists which gives

Result 2

ColumnName2

[AAA,1000)]

[AAA,1),2000)]

but again, I don't know how to create a column that uses the last element of each list.

I can get it for a particular index, but not for the whole column

x = df['ColumnName'].str.split('(',expand=True) gives Result 1 above

x = df['ColumnName'].str.split('(') gives Result 2 above

From Result 2, I did the following to get the desired result for one particular cell, but I don't know how to do it for the whole column (I can do this for a small dataset, but not for a large one)

retrieves the list of a particular index, gets the last element of the list, splits it by spaces, and then retrieves the new element of the split list

x[0][-1].split()[0]
x[1][-1].split()[0]

Body:
You could use str.extract to match the digits inside the parenthesis, and add '$' so it matches only at the end of the string:

df.assign(Column_cost = df.ColumnName.str.extract(r'\((\d+)\)$'))

       ColunmName    Column_cost
0      AAA (1000)        1000
1  AAA (1) (2000)        2000


问:
Jenkins dsl configure block makes duplicate tabs
I'm trying to create a job DSL which creates a multibranch-pipeline job,
The job is being created successfully but there are some missing configurations in the multi-pipeline job so I tried to use the "configure" block.

The configure block indeed was created but it created a duplicate "tag" of jenkins.branch.BranchSource I guess I am missing something' I tried tons of manipulations but nothing worked for me.
Any advice?

This is my groovy DSL:

```<code>multibranchPipelineJob('TestDocker_pipeline_DSL') {

    branchSources {
        git {
            remote(gitUrl)
            credentialsId('Dev_Builder_ssh')
            //includes("(V[0-9]+.[0-9]+([.]+[0-9]+)*)|(master)")
        }
        configure {
            it / sources / data / "jenkins.branch.BranchSource" << "jenkins.plugins.git.GitSCMSource"  {
                id("8fd33e1d-07b6-4cc4-8f1c-a18d955b4b6e")
                remote(gitUrl)
                credentialsId('Dev_Builder_ssh')
                traits{
                    "jenkins.scm.impl.trait.RegexSCMHeadFilterTrait"{
                        regex("V[0-9]+.[0-9]+([.]+[0-9]+)*)|(master)")
                    }
                }
            }
        }
    }
    factory {
        workflowBranchProjectFactory {
            scriptPath('main/Docker/DockerJenkinsfileSlave.groovy')
        }
    }
    orphanedItemStrategy {
        discardOldItems {
            numToKeep(3)
        }
    }
}
</code>```

And this is the job XML being created:

答:
Well After a lot of struggling I think that my problem was that I didn't define some of the TAGS as plugins in the groovy DSL and removing the "git" section also helped.

So the Final groovy that finally worked was this one:

```<code>branchSources {
    configure {
        it / sources / data / "jenkins.branch.BranchSource" <<  source (class: "jenkins.plugins.git.GitSCMSource", plugin:"git@3.9.2")  {
            remote(gitUrl)
            credentialsId('Dev_Builder_ssh')
            includes('*')
            excludes('')
            ignoreOnPushNotifications(false)
            traits{
                "jenkins.scm.impl.trait.RegexSCMHeadFilterTrait"{
                    regex("(V[0-9]+.[0-9]+([.]+[0-9]+)*)|(master)")
                }
            }
        }
    }
}
</code>```

Which resulted this beutifull XML job:

Body:
I'm trying to create a job DSL which creates a multibranch-pipeline job,
The job is being created successfully but there are some missing configurations in the multi-pipeline job so I tried to use the "configure" block.

The configure block indeed was created but it created a duplicate "tag" of jenkins.branch.BranchSource I guess I am missing something' I tried tons of manipulations but nothing worked for me.
Any advice?

This is my groovy DSL:

multibranchPipelineJob('TestDocker_pipeline_DSL') {

    branchSources {
        git {
            remote(gitUrl)
            credentialsId('Dev_Builder_ssh')
            //includes("(V[0-9]+.[0-9]+([.]+[0-9]+)*)|(master)")
        }
        configure {
            it / sources / data / "jenkins.branch.BranchSource" << "jenkins.plugins.git.GitSCMSource"  {
                id("8fd33e1d-07b6-4cc4-8f1c-a18d955b4b6e")
                remote(gitUrl)
                credentialsId('Dev_Builder_ssh')
                traits{
                    "jenkins.scm.impl.trait.RegexSCMHeadFilterTrait"{
                        regex("V[0-9]+.[0-9]+([.]+[0-9]+)*)|(master)")
                    }
                }
            }
        }
    }
    factory {
        workflowBranchProjectFactory {
            scriptPath('main/Docker/DockerJenkinsfileSlave.groovy')
        }
    }
    orphanedItemStrategy {
        discardOldItems {
            numToKeep(3)
        }
    }
}

And this is the job XML being created:

Body:
Well After a lot of struggling I think that my problem was that I didn't define some of the TAGS as plugins in the groovy DSL and removing the "git" section also helped.

So the Final groovy that finally worked was this one:

branchSources {
    configure {
        it / sources / data / "jenkins.branch.BranchSource" <<  source (class: "jenkins.plugins.git.GitSCMSource", plugin:"git@3.9.2")  {
            remote(gitUrl)
            credentialsId('Dev_Builder_ssh')
            includes('*')
            excludes('')
            ignoreOnPushNotifications(false)
            traits{
                "jenkins.scm.impl.trait.RegexSCMHeadFilterTrait"{
                    regex("(V[0-9]+.[0-9]+([.]+[0-9]+)*)|(master)")
                }
            }
        }
    }
}

Which resulted this beutifull XML job:


问:
How Do You Tell What Next Identity Column Will Be?
Is there a tsql query to tell what SQL server identity column value it expects to use for the next row insert?

Edited to add:

I deleted and recreated a table with

```<code>[personID] [int] IDENTITY(1,1) NOT NULL
</code>```

as part of my CREATE TABLE command.  I've also attempted to reseed identity columns while removing all information in that table and that hasn't always worked.  It got me to wondering if there was a way to see what SQL expected to use for your next identity column number.

答:
This piece of sql will give you the next identity column value (there are probably many reasons not to repeat this snippet in production code)

```<code>declare @nextid int;
declare @previousid int;

begin tran

 insert into dbo.TestTable (Col1) values ('11');
 select @nextid = SCOPE_IDENTITY();

rollback tran

 select @previousid = @nextid -1
 DBCC CHECKIDENT('dbo.TestTable', RESEED, @previousid);
 select @nextid
</code>```

this stackoverflow question gives some extra information - sql-identity-autonumber-is-incremented-even-with-a-transaction-rollback

OwnerDisplayName: GregD

ContentLicense: CC BY-SA 2.5

Body:
Is there a tsql query to tell what SQL server identity column value it expects to use for the next row insert?

Edited to add:

I deleted and recreated a table with

[personID] [int] IDENTITY(1,1) NOT NULL

as part of my CREATE TABLE command.  I've also attempted to reseed identity columns while removing all information in that table and that hasn't always worked.  It got me to wondering if there was a way to see what SQL expected to use for your next identity column number.

LastEditorDisplayName: Cade Roux

Body:
This piece of sql will give you the next identity column value (there are probably many reasons not to repeat this snippet in production code)

declare @nextid int;
declare @previousid int;

begin tran

 insert into dbo.TestTable (Col1) values ('11');
 select @nextid = SCOPE_IDENTITY();

rollback tran

 select @previousid = @nextid -1
 DBCC CHECKIDENT('dbo.TestTable', RESEED, @previousid);
 select @nextid

this stackoverflow question gives some extra information - sql-identity-autonumber-is-incremented-even-with-a-transaction-rollback

OwnerDisplayName: Paul


问:
How to merge multiple dataframes
I have different dataframes and need to merge them together based on the date column. If I only had two dataframes, I could use df1.merge(df2, on='date'), to do it with three dataframes, I use df1.merge(df2.merge(df3, on='date'), on='date'), however it becomes really complex and unreadable to do it with multiple dataframes.

All dataframes have one column in common -date, but they don't have the same number of rows nor columns and I only need those rows in which each date is common to every dataframe.

So, I'm trying to write a recursion function that returns a dataframe with all data but it didn't work. How should I merge multiple dataframes then?

I tried different ways and got errors like out of range, keyerror 0/1/2/3 and can not merge DataFrame with instance of type <class 'NoneType'>.

This is the script I wrote:

```<code>dfs = [df1, df2, df3] # list of dataframes

def mergefiles(dfs, countfiles, i=0):
    if i == (countfiles - 2): # it gets to the second to last and merges it with the last
        return

    dfm = dfs[i].merge(mergefiles(dfs[i+1], countfiles, i=i+1), on='date')
    return dfm

print(mergefiles(dfs, len(dfs)))
</code>```

An example:
df_1:

```<code>May 19, 2017;1,200.00;0.1%
May 18, 2017;1,100.00;0.1%
May 17, 2017;1,000.00;0.1%
May 15, 2017;1,901.00;0.1%
</code>```

df_2:

```<code>May 20, 2017;2,200.00;1000000;0.2%
May 18, 2017;2,100.00;1590000;0.2%
May 16, 2017;2,000.00;1230000;0.2%
May 15, 2017;2,902.00;1000000;0.2%
</code>```

df_3:

```<code>May 21, 2017;3,200.00;2000000;0.3%
May 17, 2017;3,100.00;2590000;0.3%
May 16, 2017;3,000.00;2230000;0.3%
May 15, 2017;3,903.00;2000000;0.3%
</code>```

Expected merge result:

```<code>May 15, 2017;  1,901.00;0.1%;  2,902.00;1000000;0.2%;   3,903.00;2000000;0.3%
</code>```

答:
functools.reduce and pd.concat are good solutions but in term of execution time pd.concat is the best.

```<code>from functools import reduce
import pandas as pd

dfs = [df1, df2, df3, ...]
nan_value = 0

# solution 1 (fast)
result_1 = pd.concat(dfs, join='outer', axis=1).fillna(nan_value)

# solution 2
result_2 = reduce(lambda df_left,df_right: pd.merge(df_left, df_right,
                                              left_index=True, right_index=True,
                                              how='outer'),
                  dfs).fillna(nan_value)
</code>```

Title: How to merge multiple dataframes

Body:
I have different dataframes and need to merge them together based on the date column. If I only had two dataframes, I could use df1.merge(df2, on='date'), to do it with three dataframes, I use df1.merge(df2.merge(df3, on='date'), on='date'), however it becomes really complex and unreadable to do it with multiple dataframes.

All dataframes have one column in common -date, but they don't have the same number of rows nor columns and I only need those rows in which each date is common to every dataframe.

So, I'm trying to write a recursion function that returns a dataframe with all data but it didn't work. How should I merge multiple dataframes then?

I tried different ways and got errors like out of range, keyerror 0/1/2/3 and can not merge DataFrame with instance of type <class 'NoneType'>.

This is the script I wrote:

dfs = [df1, df2, df3] # list of dataframes

def mergefiles(dfs, countfiles, i=0):
    if i == (countfiles - 2): # it gets to the second to last and merges it with the last
        return

    dfm = dfs[i].merge(mergefiles(dfs[i+1], countfiles, i=i+1), on='date')
    return dfm

print(mergefiles(dfs, len(dfs)))

An example:
df_1:

May 19, 2017;1,200.00;0.1%
May 18, 2017;1,100.00;0.1%
May 17, 2017;1,000.00;0.1%
May 15, 2017;1,901.00;0.1%

df_2:

May 20, 2017;2,200.00;1000000;0.2%
May 18, 2017;2,100.00;1590000;0.2%
May 16, 2017;2,000.00;1230000;0.2%
May 15, 2017;2,902.00;1000000;0.2%

df_3:

May 21, 2017;3,200.00;2000000;0.3%
May 17, 2017;3,100.00;2590000;0.3%
May 16, 2017;3,000.00;2230000;0.3%
May 15, 2017;3,903.00;2000000;0.3%

Expected merge result:

May 15, 2017;  1,901.00;0.1%;  2,902.00;1000000;0.2%;   3,903.00;2000000;0.3%

Body:
functools.reduce and pd.concat are good solutions but in term of execution time pd.concat is the best.

from functools import reduce
import pandas as pd

dfs = [df1, df2, df3, ...]
nan_value = 0

# solution 1 (fast)
result_1 = pd.concat(dfs, join='outer', axis=1).fillna(nan_value)

# solution 2
result_2 = reduce(lambda df_left,df_right: pd.merge(df_left, df_right,
                                              left_index=True, right_index=True,
                                              how='outer'),
                  dfs).fillna(nan_value)


问:
Tix ComboBox causes python2.7 to crash
I've been using Tix to create a comboBox and it causes an intermittent crash if the entry box is left empty.

I'm new to Python and very new to GUI programming so I've been using example to teach myself stuff.

When using the following example code, you should be able to enter a value into the entry box or select form the dropdown menu, however if you leave the entry field empty and press go it will cause the  python to crash.

```<code>import Tix
import tkMessageBox

class App(object):
    def __init__(self, window):
        window.winfo_toplevel().wm_title("test")
        self.window = window

        self.combo = Tix.ComboBox(window)
        self.combo.insert(Tix.END, 'thing1')
        self.combo.insert(Tix.END, 'thing2')
        self.combo.entry['state'] = "normal"
        self.combo['editable'] = True
        self.combo.pack()

        button = Tix.Button(window)
        button['text'] = "Go"
        button['command'] = self.go
        button.pack()

    def go(self):
        tkMessageBox.showinfo('info', self.combo['selection'])

if __name__ == '__main__':
    root = Tix.Tk()
    App(root)
    root.mainloop()
</code>```

=========================
CRASH DETAILS :

```<code>  Problem signature:
  Problem Event Name:   APPCRASH
  Application Name: python2.7.exe
  Application Version:  0.0.0.0
  Application Timestamp:    4cfbf049
  Fault Module Name:    ntdll.dll
  Fault Module Version: 6.1.7600.16385
  Fault Module Timestamp:   4a5bdb3b
  Exception Code:   c0000005
  Exception Offset: 0002e23e
  OS Version:   6.1.7600.2.0.0.256.48
  Locale ID:    2057
  Additional Information 1: 0a9e
  Additional Information 2: 0a9e372d3b4ad19135b953a78882e789
  Additional Information 3: 0a9e
  Additional Information 4: 0a9e372d3b4ad19135b953a78882e789
</code>```

So

A] is it something the example is doing wrong ?

B] is there a better way?

C] Should I be using Tix at all ?

I've noticed that some people seem to shy away from Tix and only use Tkinter. is there a reason for this? Should I not be using Tix ?

++++++++++++++++++++++++++++

Ok so I managed to monkeypatch this by adding value =' ' so the return string is not empty and then lstrip() the value when I need it.

```<code>self.combo = Tix.ComboBox(window, value =' ')
...
tkMessageBox.showinfo('info', self.combo['selection'].lstrip())
</code>```

Very ugly but stops me from crashing for now; until someone wiser can give me a better answer.
If the user deletes the space and then presses 'go' it will of cause crash again!

答:
I am not Tix expert, but this should fix the problem:

```<code>tkMessageBox.showinfo('info', self.combo.entry.get())
</code>```

In between the lines, I would recommend using wxPython for learning GUI programming. It was great for me as a learning environment.

```<code>import wx

class MainWin(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)

        self.combo = wx.ComboBox(self, choices=["Thing 1", "Thing 2"])
        self.button = wx.Button(self, label="Go")
        self.button.Bind(wx.EVT_BUTTON, self.OnButton)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.combo, 0, wx.EXPAND)
        self.sizer.Add(self.button, 0, wx.EXPAND)
        self.SetSizerAndFit(self.sizer)

        self.Show()

    def OnButton(self, e):
        wx.MessageBox(self.combo.GetValue())

app = wx.App(False)
main_win = MainWin(None)
app.MainLoop()
</code>```

Title: Tix ComboBox causes python2.7 to crash

Body:
I've been using Tix to create a comboBox and it causes an intermittent crash if the entry box is left empty.

I'm new to Python and very new to GUI programming so I've been using example to teach myself stuff.

When using the following example code, you should be able to enter a value into the entry box or select form the dropdown menu, however if you leave the entry field empty and press go it will cause the  python to crash.

import Tix
import tkMessageBox

class App(object):
    def __init__(self, window):
        window.winfo_toplevel().wm_title("test")
        self.window = window

        self.combo = Tix.ComboBox(window)
        self.combo.insert(Tix.END, 'thing1')
        self.combo.insert(Tix.END, 'thing2')
        self.combo.entry['state'] = "normal"
        self.combo['editable'] = True
        self.combo.pack()

        button = Tix.Button(window)
        button['text'] = "Go"
        button['command'] = self.go
        button.pack()

    def go(self):
        tkMessageBox.showinfo('info', self.combo['selection'])

if __name__ == '__main__':
    root = Tix.Tk()
    App(root)
    root.mainloop()

=========================
CRASH DETAILS :

  Problem signature:
  Problem Event Name:   APPCRASH
  Application Name: python2.7.exe
  Application Version:  0.0.0.0
  Application Timestamp:    4cfbf049
  Fault Module Name:    ntdll.dll
  Fault Module Version: 6.1.7600.16385
  Fault Module Timestamp:   4a5bdb3b
  Exception Code:   c0000005
  Exception Offset: 0002e23e
  OS Version:   6.1.7600.2.0.0.256.48
  Locale ID:    2057
  Additional Information 1: 0a9e
  Additional Information 2: 0a9e372d3b4ad19135b953a78882e789
  Additional Information 3: 0a9e
  Additional Information 4: 0a9e372d3b4ad19135b953a78882e789

So

A] is it something the example is doing wrong ?

B] is there a better way?

C] Should I be using Tix at all ?

I've noticed that some people seem to shy away from Tix and only use Tkinter. is there a reason for this? Should I not be using Tix ?

++++++++++++++++++++++++++++

Ok so I managed to monkeypatch this by adding value =' ' so the return string is not empty and then lstrip() the value when I need it.

self.combo = Tix.ComboBox(window, value =' ')
...
tkMessageBox.showinfo('info', self.combo['selection'].lstrip())

Very ugly but stops me from crashing for now; until someone wiser can give me a better answer.
If the user deletes the space and then presses 'go' it will of cause crash again!

Body:
I am not Tix expert, but this should fix the problem:

tkMessageBox.showinfo('info', self.combo.entry.get())

In between the lines, I would recommend using wxPython for learning GUI programming. It was great for me as a learning environment.

import wx

class MainWin(wx.Frame):
    def __init__(self, *args, **kwargs):
        wx.Frame.__init__(self, *args, **kwargs)

        self.combo = wx.ComboBox(self, choices=["Thing 1", "Thing 2"])
        self.button = wx.Button(self, label="Go")
        self.button.Bind(wx.EVT_BUTTON, self.OnButton)

        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.combo, 0, wx.EXPAND)
        self.sizer.Add(self.button, 0, wx.EXPAND)
        self.SetSizerAndFit(self.sizer)

        self.Show()

    def OnButton(self, e):
        wx.MessageBox(self.combo.GetValue())

app = wx.App(False)
main_win = MainWin(None)
app.MainLoop()


问:
Modify scheduler timing dynamically based on the condition used with spring-boot @Scheduled annotation
I have a scheduler, which triggers at a fixed delay of 5secs. I am planning to have more than one schedulers, but for now, let's stick to just one scheduler.

Requirement: Based on business condition scheduler's fixedDelay should be changed (e.g, default fixedDelay is 5secs, but it can be 6, 8, 10secs, based on condition).

In order to achieve this, I am trying to modify the fixedDelay. But it's not working for me.

Interface, with delay methods

```<code>public abstract class DynamicSchedule{
        /**
         * Delays scheduler
         * @param milliseconds - the time to delay scheduler.
         */
        abstract void delay(Long milliseconds);

        /**
         * Decreases delay period
         * @param milliseconds - the time to decrease delay period.
         */
        abstract void decreaseDelayInterval(Long milliseconds);

        /**
         * Increases delay period
         * @param milliseconds - the time to increase dela period
        */
        abstract void increaseDelayInterval(Long milliseconds);
}
</code>```

Implementating Trigger interface that is located at org.springframework.scheduling in the spring-context project.

```<code>import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;

import java.util.Date;
import java.util.concurrent.ScheduledFuture;

public class CustomDynamicSchedule extends DynamicSchedule implements Trigger {

    private TaskScheduler taskScheduler;
    private ScheduledFuture<?> schedulerFuture;

    /**
     * milliseconds
     */
    private long delayInterval;

    public CustomDynamicSchedule(TaskScheduler taskScheduler) {
        this.taskScheduler = taskScheduler;
    }

    @Override
    public void increaseDelayInterval(Long delay) {
        if (schedulerFuture != null) {
            schedulerFuture.cancel(true);
        }
        this.delayInterval += delay;
        schedulerFuture = taskScheduler.schedule(() -> { }, this);
    }

    @Override
    public void decreaseDelayInterval(Long delay) {
        if (schedulerFuture != null) {
            schedulerFuture.cancel(true);
        }
        this.delayInterval += delay;
        schedulerFuture = taskScheduler.schedule(() -> { }, this);
    }

    @Override
    public void delay(Long delay) {
        if (schedulerFuture != null) {
            schedulerFuture.cancel(true);
        }
        this.delayInterval = delay;
        schedulerFuture = taskScheduler.schedule(() -> { }, this);
    }

    @Override
    public Date nextExecutionTime(TriggerContext triggerContext) {
        Date lastTime = triggerContext.lastActualExecutionTime();
        return (lastTime == null) ? new Date() : new Date(lastTime.getTime() + delayInterval);
    }
}
</code>```

configuration:

```<code>@Configuration
public class DynamicSchedulerConfig {
    @Bean
    public CustomDynamicSchedule getDinamicScheduler() {
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
        threadPoolTaskScheduler.initialize();
        return  new CustomDynamicSchedule(threadPoolTaskScheduler);
    }
}
</code>```

Test class, to test the usage.

```<code>@EnableScheduling
@Component
public class TestSchedulerComponent {

    @Autowired
    private CustomDynamicSchedule dynamicSchedule;

    @Scheduled(fixedDelay = 5000)
    public void testMethod() {
        dynamicSchedule.delay(1000l);
        dynamicSchedule.increaseDelayInterval(9000l);
        dynamicSchedule.decreaseDelayInterval(5000l);
    }

}
</code>```

I have tried to use https://stackoverflow.com/a/51333059/4770397 but this code is not working for me.

Scheduler is running at fixedDelay, there is no change in that.

答:
Spring's @Scheduled annotation does not provide this support.

This is my preferred implementation of a similar feature using a Queue-based solution which allows flexibility of timing and very robust implementation of this scheduler functionality.

This is the pipeline-

Cron Maintainer and Publisher- For every task, there is an affiliated cron and a single-threaded executor service which is responsible for publishing messages to the Queue as per the cron. The task-cron mappings are persisted in the database and are initialized during the startup. Also, we have an API exposed to update cron for a task at runtime.

We simply shut down the old scheduled executor service and create a one whenever we trigger a change in the cron via our API. Also, we update the same in the database.

Queue- Used for storing messages published by the publisher.

Scheduler- This is where the business logic of the schedulers reside. A listener on the Queue(Kafka, in our case) listens for the incoming messages and invokes the corresponding scheduler task in a new thread whenever it receives a message for the same.

There are various advantages to this approach. This decouples the scheduler from the schedule management task. Now, the scheduler can focus on business logic alone. Also, we can write as many schedulers as we want, all listening to the same queue and acting accordingly.

Body:
I have a scheduler, which triggers at a fixed delay of 5secs. I am planning to have more than one schedulers, but for now, let's stick to just one scheduler.

Requirement: Based on business condition scheduler's fixedDelay should be changed (e.g, default fixedDelay is 5secs, but it can be 6, 8, 10secs, based on condition).

In order to achieve this, I am trying to modify the fixedDelay. But it's not working for me.

Interface, with delay methods

public abstract class DynamicSchedule{
        /**
         * Delays scheduler
         * @param milliseconds - the time to delay scheduler.
         */
        abstract void delay(Long milliseconds);

        /**
         * Decreases delay period
         * @param milliseconds - the time to decrease delay period.
         */
        abstract void decreaseDelayInterval(Long milliseconds);

        /**
         * Increases delay period
         * @param milliseconds - the time to increase dela period
        */
        abstract void increaseDelayInterval(Long milliseconds);
}

Implementating Trigger interface that is located at org.springframework.scheduling in the spring-context project.

import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;

import java.util.Date;
import java.util.concurrent.ScheduledFuture;

public class CustomDynamicSchedule extends DynamicSchedule implements Trigger {

    private TaskScheduler taskScheduler;
    private ScheduledFuture<?> schedulerFuture;

    /**
     * milliseconds
     */
    private long delayInterval;

    public CustomDynamicSchedule(TaskScheduler taskScheduler) {
        this.taskScheduler = taskScheduler;
    }

    @Override
    public void increaseDelayInterval(Long delay) {
        if (schedulerFuture != null) {
            schedulerFuture.cancel(true);
        }
        this.delayInterval += delay;
        schedulerFuture = taskScheduler.schedule(() -> { }, this);
    }

    @Override
    public void decreaseDelayInterval(Long delay) {
        if (schedulerFuture != null) {
            schedulerFuture.cancel(true);
        }
        this.delayInterval += delay;
        schedulerFuture = taskScheduler.schedule(() -> { }, this);
    }

    @Override
    public void delay(Long delay) {
        if (schedulerFuture != null) {
            schedulerFuture.cancel(true);
        }
        this.delayInterval = delay;
        schedulerFuture = taskScheduler.schedule(() -> { }, this);
    }

    @Override
    public Date nextExecutionTime(TriggerContext triggerContext) {
        Date lastTime = triggerContext.lastActualExecutionTime();
        return (lastTime == null) ? new Date() : new Date(lastTime.getTime() + delayInterval);
    }
}

configuration:

@Configuration
public class DynamicSchedulerConfig {
    @Bean
    public CustomDynamicSchedule getDinamicScheduler() {
        ThreadPoolTaskScheduler threadPoolTaskScheduler = new ThreadPoolTaskScheduler();
        threadPoolTaskScheduler.initialize();
        return  new CustomDynamicSchedule(threadPoolTaskScheduler);
    }
}

Test class, to test the usage.

@EnableScheduling
@Component
public class TestSchedulerComponent {

    @Autowired
    private CustomDynamicSchedule dynamicSchedule;

    @Scheduled(fixedDelay = 5000)
    public void testMethod() {
        dynamicSchedule.delay(1000l);
        dynamicSchedule.increaseDelayInterval(9000l);
        dynamicSchedule.decreaseDelayInterval(5000l);
    }

}

I have tried to use https://stackoverflow.com/a/51333059/4770397 but this code is not working for me.

Scheduler is running at fixedDelay, there is no change in that.


问:
Bigquery data not getting inserted
I'm using python client library to insert data to big query table. The code is as follows.

```<code>client = bigquery.Client(project_id)
errors = client.insert_rows_json(table=tablename,json_rows=data_to_insert)
assert errors == []
</code>```

There are no errors, but the data is also not getting inserted.

Sample JSON rows:

```<code>[{'a':'b','c':'d'},{'a':'f','q':'r'},.....}]
</code>```

What's the problem? No exception also

答:
It can be 2 possible situations:

your data does not match the schema

your table is freshly created, and the update is just not yet available

References:

Related GitHub issue

Data availability

Title: Bigquery data not getting inserted

Body:
I'm using python client library to insert data to big query table. The code is as follows.

client = bigquery.Client(project_id)
errors = client.insert_rows_json(table=tablename,json_rows=data_to_insert)
assert errors == []

There are no errors, but the data is also not getting inserted.

Sample JSON rows:

[{'a':'b','c':'d'},{'a':'f','q':'r'},.....}]

What's the problem? No exception also


问:
What's lazy about views on Scala's mutable collections?
I think this question is essentially about what laziness is in the context of mutability.

In Programming in Scala (or the docs), they give examples of how to use views on immutable and mutable collections. In that section, they state

[transformer methods] take at least one collection as their receiver object and produce another collection in their result. ... A view is a special kind of collection that represents some base collection, but implements all of its transformers lazily.

They give examples with immutable collections and I understand how laziness works there. But I'm struggling with the role laziness plays in the example with a mutable collection:

Many transformer functions on [views over mutable sequences] provide a window into the original sequence ... an example ...

```<code>val arr = (0 to 9).toArray
val subarr = arr.view.slice(3, 6)
</code>```

The view does not copy these elements, it just provides a reference to them.

```<code>def negate(xs: collection.mutable.Seq[Int]) =
  for (i <- 0 until xs.length) xs(i) = - xs(i)

negate(subarr)
arr  // Array(0, 1, 2, -3, -4, -5, 6, 7, 8, 9)
</code>```

I understand why we get that answer. But what is lazy about the transformer slice? I had understood laziness to mean that values are only computed when needed (like with the immutable collections examples). But the values in slice are never computed, they are just references to those in arr, even after calling negate. Is this my misunderstanding of laziness? Or are the docs using laziness in another way? Or something else?

答:
Here's a better example of this lazy behavior:</p>

```<code>val a = Array(1,2,3)
val b = a.map(_ + 5)
val c = a.view.map(_ + 5)
println(b(1)) //prints 7
println(c(1)) // prints 7

a(1) = 5

println(b(1)) // still prints 7, since that array was computed on instantiation
println(c(1)) // now prints 10, since elements of c are lazily evaluated each time.
</code>```

Body:
I think this question is essentially about what laziness is in the context of mutability.

In Programming in Scala (or the docs), they give examples of how to use views on immutable and mutable collections. In that section, they state

[transformer methods] take at least one collection as their receiver object and produce another collection in their result. ... A view is a special kind of collection that represents some base collection, but implements all of its transformers lazily.

They give examples with immutable collections and I understand how laziness works there. But I'm struggling with the role laziness plays in the example with a mutable collection:

Many transformer functions on [views over mutable sequences] provide a window into the original sequence ... an example ...

val arr = (0 to 9).toArray
val subarr = arr.view.slice(3, 6)

The view does not copy these elements, it just provides a reference to them.

def negate(xs: collection.mutable.Seq[Int]) =
  for (i <- 0 until xs.length) xs(i) = - xs(i)

negate(subarr)
arr  // Array(0, 1, 2, -3, -4, -5, 6, 7, 8, 9)

I understand why we get that answer. But what is lazy about the transformer slice? I had understood laziness to mean that values are only computed when needed (like with the immutable collections examples). But the values in slice are never computed, they are just references to those in arr, even after calling negate. Is this my misunderstanding of laziness? Or are the docs using laziness in another way? Or something else?

Body:
Here's a better example of this lazy behavior:

val a = Array(1,2,3)
val b = a.map(_ + 5)
val c = a.view.map(_ + 5)
println(b(1)) //prints 7
println(c(1)) // prints 7

a(1) = 5

println(b(1)) // still prints 7, since that array was computed on instantiation
println(c(1)) // now prints 10, since elements of c are lazily evaluated each time.


问:
Django testing - test if logged in user is owner of userdetails
So I've made this little app where users have an account page were they can see and update their own details.

Now I'm writing some tests for the DetailView and UpdateView. I would like to verify that the logged in user is indeed the owner of the user details.

I've created a testdatabase with different users and added three tests.

Check if the user is logged in

When a user is logged in does he get the right template

When a user is logged in does he see his own details only

The problem is in the last test, I tried to retrieve the logged in user and compare this with the current user details but this isn't working. Any ideas?

Edit: The test now passes successfully, so the user data belongs to the user who is logged in.

However this doesn't feel like a valid test method. Even though the user matches the owner of the details I'm looking for a way to verify if a user would be able to access the details of someone else.

Before, I would use the user id in the url like;

urls.py

```<code>path('account/<int:pk>/', views.AccountDetailView.as_view(), name='account_detail'),
</code>```

So someone would be able to edit the urlpath and access someone else his details if the LoginRequiredMixin wasn't added.

By using get_object(self):, this is no longer possible, what's the best way to test this possibility?

views.py

```<code>class AccountDetailView(LoginRequiredMixin, DetailView):
    model = User
    template_name = 'account.html'

    '''
    Retrieve user id from "self.request.user" instead of retrieving the user_id
    from the URL. This way we can eliminate the user id in the URL.
    '''
    def get_object(self):
        return self.request.user
</code>```

test_views.py

```<code>class LoggedInTestCase(TestCase):
    '''
    Setup LoginInTestCase
    '''
    def setUp(self):
        guest = User.objects.create_user(username='john.doe', email='john@doe.com', password='1234')
        guest_other = User.objects.create_user(username='david.doe', email='david@doe.com', password='5678')

class AccountDetailViewTests(LoggedInTestCase):
    '''
    Test the UserDetailView which shows the user details
    '''
    def test_login_required_redirection(self):
        '''
        Test if only logged in users can view the user detail page
        '''
        self.url = reverse('account_detail')
        login_url = reverse('account_login')
        response = self.client.get(self.url)
        self.assertRedirects(response, '{login_url}?next={url}'.format(login_url=login_url, url=self.url))

    def test_logged_in_uses_correct_template(self):
        '''
        Test if logged in user gets to see the correct template
        '''
        login = self.client.login(username='john.doe', password='1234')
        response = self.client.get(reverse('account_detail'))
        # Check if our guest is logged in
        self.assertEqual(str(response.context['user']), 'john.doe')
        # Check for response "succes"
        self.assertEqual(response.status_code, 200)
        # Check if we get the correct template
        self.assertTemplateUsed(response, 'account.html')

    def test_accountdetails_belong_to_logged_in_user(self):
        '''
        Test if logged in user can only see the details that belong to him
        '''
        login = self.client.login(username='john.doe', password='1234')
        response = self.client.get(reverse('account_detail'))
        # Check if our guest is logged in matches the
        user = User.objects.get(username='john.doe') #edited
        self.assertEqual(response.context['user'], user)
        # Check for response "success"
        self.assertEqual(response.status_code, 200)
</code>```

答:
The client.login method returns True if the login succeeded, it does not return the user.

You can fetch the user from the database.

```<code>user = User.objects.get(username='john.doe')
self.assertEqual(response.context['user'], user)
</code>```

Or compare the string as in your other test.

```<code>self.assertEqual(str(response.context['user']), 'john.doe')
</code>```

Body:
So I've made this little app where users have an account page were they can see and update their own details.

Now I'm writing some tests for the DetailView and UpdateView. I would like to verify that the logged in user is indeed the owner of the user details.

I've created a testdatabase with different users and added three tests.

Check if the user is logged in

When a user is logged in does he get the right template

When a user is logged in does he see his own details only

The problem is in the last test, I tried to retrieve the logged in user and compare this with the current user details but this isn't working. Any ideas?

Edit: The test now passes successfully, so the user data belongs to the user who is logged in.

However this doesn't feel like a valid test method. Even though the user matches the owner of the details I'm looking for a way to verify if a user would be able to access the details of someone else.

Before, I would use the user id in the url like;

urls.py

path('account/<int:pk>/', views.AccountDetailView.as_view(), name='account_detail'),

So someone would be able to edit the urlpath and access someone else his details if the LoginRequiredMixin wasn't added.

By using get_object(self):, this is no longer possible, what's the best way to test this possibility?

views.py

class AccountDetailView(LoginRequiredMixin, DetailView):
    model = User
    template_name = 'account.html'

    '''
    Retrieve user id from "self.request.user" instead of retrieving the user_id
    from the URL. This way we can eliminate the user id in the URL.
    '''
    def get_object(self):
        return self.request.user

test_views.py

class LoggedInTestCase(TestCase):
    '''
    Setup LoginInTestCase
    '''
    def setUp(self):
        guest = User.objects.create_user(username='john.doe', email='john@doe.com', password='1234')
        guest_other = User.objects.create_user(username='david.doe', email='david@doe.com', password='5678')

class AccountDetailViewTests(LoggedInTestCase):
    '''
    Test the UserDetailView which shows the user details
    '''
    def test_login_required_redirection(self):
        '''
        Test if only logged in users can view the user detail page
        '''
        self.url = reverse('account_detail')
        login_url = reverse('account_login')
        response = self.client.get(self.url)
        self.assertRedirects(response, '{login_url}?next={url}'.format(login_url=login_url, url=self.url))

    def test_logged_in_uses_correct_template(self):
        '''
        Test if logged in user gets to see the correct template
        '''
        login = self.client.login(username='john.doe', password='1234')
        response = self.client.get(reverse('account_detail'))
        # Check if our guest is logged in
        self.assertEqual(str(response.context['user']), 'john.doe')
        # Check for response "succes"
        self.assertEqual(response.status_code, 200)
        # Check if we get the correct template
        self.assertTemplateUsed(response, 'account.html')

    def test_accountdetails_belong_to_logged_in_user(self):
        '''
        Test if logged in user can only see the details that belong to him
        '''
        login = self.client.login(username='john.doe', password='1234')
        response = self.client.get(reverse('account_detail'))
        # Check if our guest is logged in matches the
        user = User.objects.get(username='john.doe') #edited
        self.assertEqual(response.context['user'], user)
        # Check for response "success"
        self.assertEqual(response.status_code, 200)

Body:
The client.login method returns True if the login succeeded, it does not return the user.

You can fetch the user from the database.

user = User.objects.get(username='john.doe')
self.assertEqual(response.context['user'], user)

Or compare the string as in your other test.

self.assertEqual(str(response.context['user']), 'john.doe')


问:
How many bytes is a gigabyte (GB)?
When I convert between 1GB to byte using online tools, I get different answers. For instance, using Google Convertor: 1GB=1e+9 while in another converter I get 1GB= 1073741824. I suppose the unit is used in different fashion based on whether 1KB=1024B or 1KB=1000B (this is Google unit).

How can I know which unit my machine uses using a small C program or function? Does C have a macro for that? I want to do that as my program will possibly be run via various operating systems.

答:
The “gibibyte” is a multiple of the unit byte for Digital
Information.

The binary prefix gibi means 2^30, therefore one gibibyte is equal to
1073741824 bytes = 1024 mebibytes.

The unit symbol for the gibibyte is GiB. It is one of the units with
binary prefixes defined by the International Electrotechnical
Commission (IEC) in 1998.

The “gibibyte” is closely related to the Gigabyte (GB), which is
defined by the IEC as 10^9 bytes = 1000000000 bytes, 1GiB ≈ 1.024GB.
1024 Gibibytes are equal to One Tebibyte.

In the context of computer memory, Gigabyte and GB are customarily
used to mean 1024^3 (2^30) bytes, although not in the context of data
transmission and not necessarily for Hard Drive size.

Title: How many bytes is a gigabyte (GB)?


问:
How can I import schemas required by a WSDL when using XML::Compile::WSDL11?
I want to build a client for a web-service using XML::Compile::WSDL11. This is the code I use:

```<code>my $wsdl = XML::Compile::WSDL11->new($wsdlfile);
my $call = $wsdl->compileClient('MyMethod', port => 'MyPort');
$call->();
</code>```

However, some operations return errors like this:

error: cannot find ref element
  '{http://www.w3.org/2001/XMLSchema}schema'
  at ...

AFAIC, this means that some schemas're missing. From the manpage:

on purpose you must explicitly load
  the files you need from local disk

How can I determine what schema files are required by the WSDL and import them automatically?

答:
The required XSD file comes with XML::Compile. You can import it like this:

```<code>my $wsdl = XML::Compile::WSDL11->new($wsdlfile);
$wsdl->importDefinitions('http://www.w3.org/2001/XMLSchema');
</code>```

See XML::Compile::Util for the list of other schemas which can be imported this way.

Body:
I want to build a client for a web-service using XML::Compile::WSDL11. This is the code I use:

my $wsdl = XML::Compile::WSDL11->new($wsdlfile);
my $call = $wsdl->compileClient('MyMethod', port => 'MyPort');
$call->();

However, some operations return errors like this:

error: cannot find ref element
  '{http://www.w3.org/2001/XMLSchema}schema'
  at ...

AFAIC, this means that some schemas're missing. From the manpage:

on purpose you must explicitly load
  the files you need from local disk

How can I determine what schema files are required by the WSDL and import them automatically?

Body:
The required XSD file comes with XML::Compile. You can import it like this:

my $wsdl = XML::Compile::WSDL11->new($wsdlfile);
$wsdl->importDefinitions('http://www.w3.org/2001/XMLSchema');

See XML::Compile::Util for the list of other schemas which can be imported this way.


问:
Communication between Items in ItemsControl without using Messenger or EventAggregator
How can Items from Bindings in a ItemsControl communicate with each other without using Messenger, or EventAggregator. Below is a simplified yet complete case. Where I have two associated items in the ItemsControl.  UpdateTheSecondItemFromTheFirstItem() can be done by using EventAggregator(messenger) in prism. But I'm wondering if there is any more direct solution to achieve this without using messenger.
MainWindow:

```<code>    <Window x:Class="WpfApp2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
  <ItemsControl ItemsSource="{Binding MyItems}">
       <ItemsControl.ItemsPanel>
          <ItemsPanelTemplate>
               <StackPanel Orientation="Vertical">
              </StackPanel>
          </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
         <DataTemplate DataType="MyType">
            <Grid>
                <Slider Value="{Binding MyNum}" Minimum="0" Maximum="100"></Slider>
            </Grid>
         </DataTemplate>
        </ItemsControl.ItemTemplate>
  </ItemsControl>
</Grid>
</code>```

MyType

```<code>   using Prism.Mvvm;

namespace WpfApp2
{
    public class MyType : BindableBase
    {
        private bool _isFirstItem=false;

        private int _myVar;

        public int MyVar
        {
            get { return _myVar; }
            set
            {
                if (Equals(_myVar, value)) return;
                SetProperty(ref _myVar, value);
            }
        }

        public MyType(bool isFirst)
        {
            _isFirstItem = isFirst;
            MyVar = 0;
        }
    }
}
</code>```

MainWindowViewModel

```<code>    using Prism.Mvvm;
using System.Collections.ObjectModel;

namespace WpfApp2
{
    public class MainWindowViewModel:BindableBase
    {
        private ObservableCollection<MyType> _myItems = new ObservableCollection<MyType>();

        public ObservableCollection<MyType> MyItems
        {
            get { return _myItems; }
            set
            {
                if (Equals(_myItems, value)) return;
                SetProperty(ref _myItems, value);
                if(_isFirstItem) UpdateTheSecondItemFromTheFirstItem();
            }
        }

        private void UpdateTheSecondItemFromTheFirstItem(){

        }

        public MainWindowViewModel()
        {
            MyType[] MyTypeArr =
            {
                new MyType(true),
                new MyType(false)
            };
            MyItems.AddRange(MyTypeArr);
        }
    }
}
</code>```

答:
Found the solution, just use ref, which is exactly like pointer in C++:

MainWindowViewModel:

```<code>        public MainWindowViewModel()
    {
        MyType Type1 = new MyType();
        MyType Type2 = new MyType();

        MyItems.Add(Type1);
        MyItems.Add(Type2);

        Type1.SetPair(ref Type2);
    }
</code>```

MyType.cs:

```<code>   using Prism.Mvvm;

namespace WpfApp2
{
    public class MyType : BindableBase
    {
        private int _myVar;

        public int MyVar
        {
            get { return _myVar; }
            set
            {
                if (Equals(_myVar, value)) return;
                SetProperty(ref _myVar, value);
                if (MyPair!=null)
                {
                    MyPair.MyVar = value;
                }
            }
        }

        public MyType()
        {
            MyVar = 0;
        }

        MyType MyPair { get; set; }

        public void SetPair(ref MyType pair)
        {
            MyPair = pair;
        }

        public MyType GetPair()
        {
            return MyPair;
        }
    }
}
</code>```

Now, when dragging the slider, the second slider will move along with the first slider.

Body:
How can Items from Bindings in a ItemsControl communicate with each other without using Messenger, or EventAggregator. Below is a simplified yet complete case. Where I have two associated items in the ItemsControl.  UpdateTheSecondItemFromTheFirstItem() can be done by using EventAggregator(messenger) in prism. But I'm wondering if there is any more direct solution to achieve this without using messenger.
MainWindow:

    <Window x:Class="WpfApp2.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:prism="http://prismlibrary.com/"
prism:ViewModelLocator.AutoWireViewModel="True"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="800">
<Grid>
  <ItemsControl ItemsSource="{Binding MyItems}">
       <ItemsControl.ItemsPanel>
          <ItemsPanelTemplate>
               <StackPanel Orientation="Vertical">
              </StackPanel>
          </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.ItemTemplate>
         <DataTemplate DataType="MyType">
            <Grid>
                <Slider Value="{Binding MyNum}" Minimum="0" Maximum="100"></Slider>
            </Grid>
         </DataTemplate>
        </ItemsControl.ItemTemplate>
  </ItemsControl>
</Grid>

MyType

   using Prism.Mvvm;

namespace WpfApp2
{
    public class MyType : BindableBase
    {
        private bool _isFirstItem=false;

        private int _myVar;

        public int MyVar
        {
            get { return _myVar; }
            set
            {
                if (Equals(_myVar, value)) return;
                SetProperty(ref _myVar, value);
            }
        }

        public MyType(bool isFirst)
        {
            _isFirstItem = isFirst;
            MyVar = 0;
        }
    }
}

MainWindowViewModel

    using Prism.Mvvm;
using System.Collections.ObjectModel;

namespace WpfApp2
{
    public class MainWindowViewModel:BindableBase
    {
        private ObservableCollection<MyType> _myItems = new ObservableCollection<MyType>();

        public ObservableCollection<MyType> MyItems
        {
            get { return _myItems; }
            set
            {
                if (Equals(_myItems, value)) return;
                SetProperty(ref _myItems, value);
                if(_isFirstItem) UpdateTheSecondItemFromTheFirstItem();
            }
        }

        private void UpdateTheSecondItemFromTheFirstItem(){

        }

        public MainWindowViewModel()
        {
            MyType[] MyTypeArr =
            {
                new MyType(true),
                new MyType(false)
            };
            MyItems.AddRange(MyTypeArr);
        }
    }
}

Body:
Found the solution, just use ref, which is exactly like pointer in C++:

MainWindowViewModel:

        public MainWindowViewModel()
    {
        MyType Type1 = new MyType();
        MyType Type2 = new MyType();

        MyItems.Add(Type1);
        MyItems.Add(Type2);

        Type1.SetPair(ref Type2);
    }

MyType.cs:

   using Prism.Mvvm;

namespace WpfApp2
{
    public class MyType : BindableBase
    {
        private int _myVar;

        public int MyVar
        {
            get { return _myVar; }
            set
            {
                if (Equals(_myVar, value)) return;
                SetProperty(ref _myVar, value);
                if (MyPair!=null)
                {
                    MyPair.MyVar = value;
                }
            }
        }

        public MyType()
        {
            MyVar = 0;
        }

        MyType MyPair { get; set; }

        public void SetPair(ref MyType pair)
        {
            MyPair = pair;
        }

        public MyType GetPair()
        {
            return MyPair;
        }
    }
}

Now, when dragging the slider, the second slider will move along with the first slider.


问:
How to correctly use shelves when working with classes in Python?
I'm making some code to learn how to use classes better. I learnt about persistence in programs and about shelves in Python.
I'm trying to make my user input some stuff, which then is used to make an object of my only class.

import shelve
filearch = shelve.open('archive')
filearch['patients'] = {}

class Patient():
    def __init__(self, name='', surname='', notes=''):
        self.name = name
        self.surname = surname
        self.notes = notes

def makeone():
    print('Insert a name')
    nome = input('Nome: ')
    print('Insert a surname')
    cognome = input('surname: ')
    print('Insert notes')
    data = input('notes: ')
    a = {'name': name, 'surname': surname, 'notes': notes}
    return a
def addone():
    users_pat = Patient(**makeone())
    return users_pat

def save(user_paz):
    return filearch['patients'].update({user_paz : a)

```

Can someone please explain me what am i doing wrong?

答:
There are a few things to fix in this code.

Firstly, it doesn't run because this line is invalid, it's missing a closing '}'.

```<code>return filearch['patients'].update({user_paz : a)
</code>```

Once that is fixed, running the code like this

```<code>user = addone()
save(user)
</code>```

results in this error:

Traceback (most recent call last):
  File "test.py", line 30, in <module>
    user = addone()
  File "test.py", line 21, in addone
    users_pat = Patient(**makeone())
  File "test.py", line 18, in makeone
    a = {'name': name, 'surname': surname, 'notes': notes}
NameError: name 'name' is not defined
```

<p>This is because in <code>makeone</code> you assign the input values to <code>nome</code>, <code>cognome</code> and <code>data</code> but try to save the non-existent variables <code>name</code>, <code>surname</code> and <code>notes</code>.</p>

<p>If we fix these names and run again we get:</p>

<pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
  File "test.py", line 31, in <module>
    save(user)
  File "test", line 26, in save
    return filearch['patients'].update({user_paz: a})
NameError: name 'a' is not defined
</code>```

In a is the name of a variable that you create in makeone, but that name is only valid inside the makeone function.  the save function only knows about the user_paz variable that you have passed to it, so change

```<code>return filearch['patients'].update({user_paz : a})
</code>```

to

```<code>return filearch['patients'].update({user_paz : user_paz})
</code>```

Finally, as mentioned in the comments, you need to close the shelve file to be sure the content are saved.

Here's an improved version of your code: it saves the input and then reports on the contents of the shelve file.

```<code>import shelve

class Patient:
    def __init__(self, name='', surname='', notes=''):
        self.name = name
        self.surname = surname
        self.notes = notes

    def __repr__(self):
        # A readable representation of a Patient object.
        return '<Patient(name={0.name}, surname={0.surname}, notes={0.notes}>'.format(self)

    # Use the same readable representation if str(patient) is called.
    __str__ = __repr__

def makeone():
    print('Insert a name')
    name = input('Nome: ')
    print('Insert a surname')
    surname = input('surname: ')
    print('Insert notes')
    notes = input('notes: ')
    a = {'name': name, 'surname': surname, 'notes': notes}
    return a

def addone():
    users_pat = Patient(**makeone())
    return users_pat

def save(user_paz):
    with shelve.open('archive') as archive:
        archive['patients'] = {user_paz.name: user_paz}
    return

def report():
    with shelve.open('archive') as archive:
        for name, patient in archive.items():
            print(name, patient)
    return

def main():
    patient = addone()
    save(patient)
    report()
    return
</code>```

Body:
I'm making some code to learn how to use classes better. I learnt about persistence in programs and about shelves in Python.
I'm trying to make my user input some stuff, which then is used to make an object of my only class.

import shelve
filearch = shelve.open('archive')
filearch['patients'] = {}

class Patient():
    def __init__(self, name='', surname='', notes=''):
        self.name = name
        self.surname = surname
        self.notes = notes

def makeone():
    print('Insert a name')
    nome = input('Nome: ')
    print('Insert a surname')
    cognome = input('surname: ')
    print('Insert notes')
    data = input('notes: ')
    a = {'name': name, 'surname': surname, 'notes': notes}
    return a
def addone():
    users_pat = Patient(**makeone())
    return users_pat

def save(user_paz):
    return filearch['patients'].update({user_paz : a)

Can someone please explain me what am i doing wrong?

Body:
There are a few things to fix in this code.

Firstly, it doesn't run because this line is invalid, it's missing a closing '}'.

return filearch['patients'].update({user_paz : a)

Once that is fixed, running the code like this

user = addone()
save(user)

results in this error:

Traceback (most recent call last):
  File "test.py", line 30, in <module>
    user = addone()
  File "test.py", line 21, in addone
    users_pat = Patient(**makeone())
  File "test.py", line 18, in makeone
    a = {'name': name, 'surname': surname, 'notes': notes}
NameError: name 'name' is not defined

This is because in makeone you assign the input values to nome, cognome and data but try to save the non-existent variables name, surname and notes.

If we fix these names and run again we get:

Traceback (most recent call last):
  File "test.py", line 31, in <module>
    save(user)
  File "test", line 26, in save
    return filearch['patients'].update({user_paz: a})
NameError: name 'a' is not defined

In a is the name of a variable that you create in makeone, but that name is only valid inside the makeone function.  the save function only knows about the user_paz variable that you have passed to it, so change

return filearch['patients'].update({user_paz : a})

to

return filearch['patients'].update({user_paz : user_paz})

Finally, as mentioned in the comments, you need to close the shelve file to be sure the content are saved.

Here's an improved version of your code: it saves the input and then reports on the contents of the shelve file.

import shelve

class Patient:
    def __init__(self, name='', surname='', notes=''):
        self.name = name
        self.surname = surname
        self.notes = notes

    def __repr__(self):
        # A readable representation of a Patient object.
        return '<Patient(name={0.name}, surname={0.surname}, notes={0.notes}>'.format(self)

    # Use the same readable representation if str(patient) is called.
    __str__ = __repr__

def makeone():
    print('Insert a name')
    name = input('Nome: ')
    print('Insert a surname')
    surname = input('surname: ')
    print('Insert notes')
    notes = input('notes: ')
    a = {'name': name, 'surname': surname, 'notes': notes}
    return a

def addone():
    users_pat = Patient(**makeone())
    return users_pat

def save(user_paz):
    with shelve.open('archive') as archive:
        archive['patients'] = {user_paz.name: user_paz}
    return

def report():
    with shelve.open('archive') as archive:
        for name, patient in archive.items():
            print(name, patient)
    return

def main():
    patient = addone()
    save(patient)
    report()
    return


问:
SACSegmentation find strange inlier
When I use SACSegmentation to find all the perpendicular planes of the floor normal vector, I always getting strange planes. The images show the input point cloud and SACSegmentation results.. . .

I have played around with the setDistanceThreshold value, and the bigger
number it is the larger strange inlier segment I have. However, I alway get the wrong
planes. I also tried to turn on and off the setOptimizeCoefficients, as well as bring the point cloud closer to origin. I even tried with different reasonable ModelTypes and MethodTypes, such as SACMODEL_NORMAL_PLANE and SACMODEL_NORMAL_PARALLEL_PLANE. However, none of them fix the issue. Could anyone provide some suggestions? Thanks in advance.

```<code>pcl::VoxelGrid<pcl::PCLPointCloud2> sor;
    sor.setInputCloud (cloudPCL2);
    sor.setLeafSize (0.01, 0.01, 0.01);
    sor.filter (*cloudPCL2_result);

    pcl::fromPCLPointCloud2 (*cloudPCL2_result, *cloud_filtered);

    cerr << "PointCloud after filtering: " << cloud_filtered->width * cloud_filtered->height << " data points." << endl;

    pcl::ModelCoefficients::Ptr coefficients (new pcl::ModelCoefficients());
    pcl::PointIndices::Ptr inliers (new pcl::PointIndices ());

    pcl::SACSegmentation<pcl::PointXYZRGB> seg;
    seg.setOptimizeCoefficients (true);

    seg.setModelType (pcl::SACMODEL_PERPENDICULAR_PLANE);
    seg.setMethodType (pcl::SAC_RANSAC);
    seg.setMaxIterations (2000);
    seg.setDistanceThreshold (0.07);
    seg.setAxis(normal);
    seg.setEpsAngle(pcl::deg2rad(20.0));

    int i = 0, nr_points = (int) cloud_filtered->points.size ();
    while (cloud_filtered->points.size () > 0.2 * nr_points) {
        seg.setInputCloud(cloud_filtered);
        seg.segment(*inliers, *coefficients);
        if (inliers->indices.size() == 0) {
            cerr << "Could not estimate a planar model for the given dataset." << endl;
            break;
        }

        extract.setInputCloud(cloud_filtered);
        extract.setIndices(inliers);
        extract.setNegative(false);
        extract.filter(*cloudOutput);

        stringstream ss;
        ss << "plane_" << i << ".pcd";
        writer.write<pcl::PointXYZRGB>(ss.str(), *cloudOutput, false);

        extract.setNegative(true);
        extract.filter(*cloudTmp);
        cerr << "PointCloud representing the planar component: " <<
cloudTmp->width * cloudTmp->height << " data points." << endl;
        cloud_filtered.swap(cloudTmp);
        i++;
    }
</code>```

I expect the SACSegmentation will only find the ground plane and ignore all the points on the wall, but instead I got these strips of the wall along with the correct ground plane.

答:
From your code+images, I can see that the first RANSAC returns you the floor, then the wall that is parallel to the floor. What you want is the wall that is perpendicular to the floor! So, the quickest way to get it is remove the parallel restriction there and go with the pcl::SACMODEL_PLANE after you got your first ransac result. e.g.

...
while (...) {
    ...
    seg.segment(*inliers, *coefficients);
    // RESET THE RANSAC MODEL TYPE
    seg.setModelType (pcl::SACMODEL_PLANE);
```

Following your starting code, you would first get a floor with your current axis restriction, then after removing the restriction, you would be able to get a lot of better result.

Title: SACSegmentation find strange inlier

Body:
When I use SACSegmentation to find all the perpendicular planes of the floor normal vector, I always getting strange planes. The images show the input point cloud and SACSegmentation results.. . .

I have played around with the setDistanceThreshold value, and the bigger
number it is the larger strange inlier segment I have. However, I alway get the wrong
planes. I also tried to turn on and off the setOptimizeCoefficients, as well as bring the point cloud closer to origin. I even tried with different reasonable ModelTypes and MethodTypes, such as SACMODEL_NORMAL_PLANE and SACMODEL_NORMAL_PARALLEL_PLANE. However, none of them fix the issue. Could anyone provide some suggestions? Thanks in advance.

pcl::VoxelGrid<pcl::PCLPointCloud2> sor;
    sor.setInputCloud (cloudPCL2);
    sor.setLeafSize (0.01, 0.01, 0.01);
    sor.filter (*cloudPCL2_result);

    pcl::fromPCLPointCloud2 (*cloudPCL2_result, *cloud_filtered);

    cerr << "PointCloud after filtering: " << cloud_filtered->width * cloud_filtered->height << " data points." << endl;

    pcl::ModelCoefficients::Ptr coefficients (new pcl::ModelCoefficients());
    pcl::PointIndices::Ptr inliers (new pcl::PointIndices ());

    pcl::SACSegmentation<pcl::PointXYZRGB> seg;
    seg.setOptimizeCoefficients (true);

    seg.setModelType (pcl::SACMODEL_PERPENDICULAR_PLANE);
    seg.setMethodType (pcl::SAC_RANSAC);
    seg.setMaxIterations (2000);
    seg.setDistanceThreshold (0.07);
    seg.setAxis(normal);
    seg.setEpsAngle(pcl::deg2rad(20.0));

    int i = 0, nr_points = (int) cloud_filtered->points.size ();
    while (cloud_filtered->points.size () > 0.2 * nr_points) {
        seg.setInputCloud(cloud_filtered);
        seg.segment(*inliers, *coefficients);
        if (inliers->indices.size() == 0) {
            cerr << "Could not estimate a planar model for the given dataset." << endl;
            break;
        }

        extract.setInputCloud(cloud_filtered);
        extract.setIndices(inliers);
        extract.setNegative(false);
        extract.filter(*cloudOutput);

        stringstream ss;
        ss << "plane_" << i << ".pcd";
        writer.write<pcl::PointXYZRGB>(ss.str(), *cloudOutput, false);

        extract.setNegative(true);
        extract.filter(*cloudTmp);
        cerr << "PointCloud representing the planar component: " <<
cloudTmp->width * cloudTmp->height << " data points." << endl;
        cloud_filtered.swap(cloudTmp);
        i++;
    }

I expect the SACSegmentation will only find the ground plane and ignore all the points on the wall, but instead I got these strips of the wall along with the correct ground plane.

Body:
From your code+images, I can see that the first RANSAC returns you the floor, then the wall that is parallel to the floor. What you want is the wall that is perpendicular to the floor! So, the quickest way to get it is remove the parallel restriction there and go with the pcl::SACMODEL_PLANE after you got your first ransac result. e.g.

...
while (...) {
    ...
    seg.segment(*inliers, *coefficients);
    // RESET THE RANSAC MODEL TYPE
    seg.setModelType (pcl::SACMODEL_PLANE);

Following your starting code, you would first get a floor with your current axis restriction, then after removing the restriction, you would be able to get a lot of better result.


问:
My class fileds are getting initialized may be because I have a @bean for the same class but in a different .java file
I am new to spring and annotations.
I started the application in debug mode and I found that by the time my code reaches init() method of Actuator below values got assigned to actVar1 and actVar2.

actVar1 has "abc" value

actVar2 has  "xyz" value

Note: My application is not yet started completely . I am just trying with debug point in init() method for a different purpose and I observed above thing.

My question is why those variables have assigned those values.

```<code>//Actuator.java
@Component
public class Actuator {
private String actVar1;
private String actVar2;
//.. some code here
@PostConstruct
public void init(){
//my debug point is here
//some code .....
}
//.. some code here

}
//Beancreator.java
@Component
public class BeanCreator {
//.. some code here
private String first="abc";
private field2 second ="xyz";
//.. some code here

@Bean
public Actuator actuator() {
Actuator actuator = new Actuator();
actuator.setActVar1(first);
actuator.setActVar2(second);
return actuatorPoller;
}
//.. some code here
}
</code>```

When I change the method name under @Bean to different one ,those values are not getting assigned .

答:
According to Spring's official documentation methods annotated with @Bean will get automatically executed and I am assuming this happens at a point in time before you would like it to happen.

To declare a bean, simply annotate a method with the @Bean annotation. When JavaConfig encounters such a method, it will execute that method and register the return value as a bean within a BeanFactory.

You can use @DependsOn annotation to control bean creation order:

Spring, by default, manages beans’ lifecycle and arranges their initialization order.

But, we can still customize it based on our needs. We can choose either the SmartLifeCycle interface or the @DependsOn annotation for managing initialization order.

We should use this annotation for specifying bean dependencies. Spring guarantees that the defined beans will be initialized before attempting an initialization of the current bean.

Read more about the use of this annotation in this article.

Body:
I am new to spring and annotations.
I started the application in debug mode and I found that by the time my code reaches init() method of Actuator below values got assigned to actVar1 and actVar2.

actVar1 has "abc" value

actVar2 has  "xyz" value

Note: My application is not yet started completely . I am just trying with debug point in init() method for a different purpose and I observed above thing.

My question is why those variables have assigned those values.

//Actuator.java
@Component
public class Actuator {
private String actVar1;
private String actVar2;
//.. some code here
@PostConstruct
public void init(){
//my debug point is here
//some code .....
}
//.. some code here

}
//Beancreator.java
@Component
public class BeanCreator {
//.. some code here
private String first="abc";
private field2 second ="xyz";
//.. some code here

@Bean
public Actuator actuator() {
Actuator actuator = new Actuator();
actuator.setActVar1(first);
actuator.setActVar2(second);
return actuatorPoller;
}
//.. some code here
}

When I change the method name under @Bean to different one ,those values are not getting assigned .


问:
Codefluent Entities and .net Identity
Now that CodeFluent Entities blog has disappeared, and after the refurbishing of the SoftFluent site, there is no more documentation available for this framework?
How it's supposed to get information about, let me say, ASP.NET Identities, jwt, aspects, templates and all that valuable information at the blog?
And what about all those we have projects tied to this platform?</p>

答:
https://www.softfluent.com/documentation/ is still available.

The blog was discontinued because too many of its articles relate to obsolete technologies but were considered by some in the public as up to date view or as valid recommendations even in nowadays context not considering their publishing dates. In 2018 it generated too many support by itself and it was decided to put it as private and provide answers to customers through support for those having support licenses or through StackOverflow only.

SoftFluent supports existing customers through their support program if they have one ( fixes, VS2019 support, questions on their usage/code, link to specific blog article if accurate or with comments).

Existing licenses are still valid, including Free and Personal.

Specific question can still be answered through this StackOverflow channel by the community of its users and sometimes support.

Title: Codefluent Entities and .net Identity


问:
How do you get the python colour scheme while using sage on VS code?
Currently, I name my files as .py while working on them, and then change them to .sage when I need to execute. Is there a way to get the python colour scheme for sage files on VS code?

There is an extension called SAGE enterprise management that claims to do it, but the instructions are a bit unclear:

It says:

Create a x3-code named folder inside your ~/.vscode/extensions/;
Copy all files in yours recent created folder;
Reload VS Code and enjoy;

I tried both copying my sage files into the folder, and the contents of the x3-extension into the folder, both of which didn't work.

答:
The instructions referred to in the question are for Sage the
accounting software, not for SageMath the Sage mathematics
software system.

In the case of SageMath, we need to tell VS Code to apply Python
formatting not only to files ending in .py, but also to files
ending in .sage. One way to do that is to use the "file to
language association" setting:

https://code.visualstudio.com/updates/vMarch#_file-to-language-association

One would add associations from "*.sage" to "python".

This related question has answers explaining where Visual
Studio Code's language extension files are located on macOS
and Windows:

Stack Overflow question 42498117


问:
How can I restore missing "generate sample content" functionality for new Flutter projects in IntelliJ IDEA CE?
The ability of the "generate sample content" popup menu for a new Flutter project in IntelliJ IDEA seems to have disappeared on my installation. (It used to work until recently)  (IntelliJ IDEA CE 2019.1.1 Build #IC-191.6707.61, Apr 16, 2019, on macOS 10.14.4)

When I click the checkbox to enable the popup menu, the menu is not populated - its just blank.  I've re-installed IntelliJ IDEA, as well as run flutter doctor in the terminal (no errors from flutter doctor), but the popup menu remains empty.

Does anybody know how to get this menu to be re-populated?

答:
I just had the same problem and I noticed that my Android SDK was not configured correctly in IntelliJ. After specifying the path to my SDK in IntelliJ's settings I can now use the "generate sample content" functionality.

Go to IntelliJ > Preferences > Appearance & Behaviour > System Settings > Android SDK and specify the Android SDK location. Presumed you've installed the Android SDK already, you'll find it on Mac OS by default at /Users/<user-name>/Library/Android/sdk and on Windows at C:\Users\<user-name>\AppData\Local\Android\sdk.

Make sure to update your IntelliJ version, Dart & Flutter plugin, Android SDK and run flutter doctor to check if everything is set up correctly.

Also checkout this issue, which describes the same problem.


问:
django.db.utils.DataError: division by zero
I am getting a error in the following line of code:

```<code>context['stock_margin'] = context['top_stock'].annotate(
                            Avg_purchase = ExpressionWrapper(F('total_puchase') / F('quantity_purchase'), output_field=FloatField()),
                            Avg_sales = ExpressionWrapper(F('total') / F('quantity'), output_field=FloatField()))
</code>```

I am new to django and cant able to figure out why this is happening..

Any idea anyone how to solve this error?

答:
I am new to django and cant able to figure out why this is happening..

PostgreSQL raises an error if you divide by zero, since dividing by zero is undefined. Most other databases return NULL in that case.

Since django-2.2, we can use NullIf [Django-doc], and thus work with:

```<code>from django.db.models.functions.comparison import <b>NullIf</b>

context['stock_margin'] = context['top_stock'].annotate(
    Avg_purchase = ExpressionWrapper(
        F('total_puchase') / <b>NullIf(</b>F('quantity_purchase')<b>, 0)</b>,
        output_field=FloatField()
    ),
    Avg_sales = ExpressionWrapper(
        F('total') / <b>NullIf(</b>F('quantity')<b>, 0)</b>,
        output_field=FloatField()
    )
)</code>```

Otherwise you can use a Case [Django-doc]:

```<code>from django.db.models import <b>Case, When</b>

context['stock_margin'] = context['top_stock'].annotate(
    Avg_purchase = Case(
        When(<b>quantity_purcase__gt=0</b>, then=F('total_puchase') / F('quantity_purchase')),
        <b>default=None,</b>
        output_field=FloatField()
    ),
    Avg_sales = Case(
        When(<b>quantity__gt=0</b>, then=F('total') / F('quantity')),
        <b>default=None,</b>
        output_field=FloatField()
    )
)</code>```

In case the purchase_quantity/quantity is thus greater than zero, we perform the division, otherwise we return None. In both cases for records where we divide by zero, we will return None.

That being said, it is a bit odd that you have objects in your database with quantity and quantity_purchase being equal to zero. Depending on the use case, you might want to check where you create these objects, and whether you want to avoid that.

Body:
I am getting a error in the following line of code:

context['stock_margin'] = context['top_stock'].annotate(
                            Avg_purchase = ExpressionWrapper(F('total_puchase') / F('quantity_purchase'), output_field=FloatField()),
                            Avg_sales = ExpressionWrapper(F('total') / F('quantity'), output_field=FloatField()))

I am new to django and cant able to figure out why this is happening..

Any idea anyone how to solve this error?

Body:
I am new to django and cant able to figure out why this is happening..

PostgreSQL raises an error if you divide by zero, since dividing by zero is undefined. Most other databases return NULL in that case.

Since django-2.2, we can use NullIf [Django-doc], and thus work with:

from django.db.models.functions.comparison import NullIf

context['stock_margin'] = context['top_stock'].annotate(
    Avg_purchase = ExpressionWrapper(
        F('total_puchase') / NullIf(F('quantity_purchase'), 0),
        output_field=FloatField()
    ),
    Avg_sales = ExpressionWrapper(
        F('total') / NullIf(F('quantity'), 0),
        output_field=FloatField()
    )
)

Otherwise you can use a Case [Django-doc]:

from django.db.models import Case, When

context['stock_margin'] = context['top_stock'].annotate(
    Avg_purchase = Case(
        When(quantity_purcase__gt=0, then=F('total_puchase') / F('quantity_purchase')),
        default=None,
        output_field=FloatField()
    ),
    Avg_sales = Case(
        When(quantity__gt=0, then=F('total') / F('quantity')),
        default=None,
        output_field=FloatField()
    )
)

In case the purchase_quantity/quantity is thus greater than zero, we perform the division, otherwise we return None. In both cases for records where we divide by zero, we will return None.

That being said, it is a bit odd that you have objects in your database with quantity and quantity_purchase being equal to zero. Depending on the use case, you might want to check where you create these objects, and whether you want to avoid that.