问:
Calculate direct dependencies among values of a dataframe in R
A data frame is given and the objective is to calculate the direct dependency value between two columns of the data frame.

```<code>c1  c2   N
a    b   30
a    c   5
a    d   10
c    a   5
b    a   10
</code>```

what we are looking for is that to get the direct dependency relations, for example, for aand b this value is ab - ba = 20.
The final result should be like this:

```<code>c1  c2   N     DepValue
a    b   30    ab - ba = 20
a    c   5     ac - ca = 0
a    d   10    ad- 0 = 10
c    a   5     ca - ac= 0
b    a   10    ba - ab = 20
</code>```

Thank you for your help.

答:
One option is to create groups with pmin and pmax values of c1 and c2 and take difference between the two values. This will return NA for groups with only one value, we can replace those NAs to the first value in the group.

```<code>library(dplyr)

df %>%
  group_by(group1 = pmin(c1, c2), group2 = pmax(c1, c2)) %>%
  mutate(dep = N[1] - N[2],
         dep = replace(dep, is.na(dep), N[1])) %>%
  ungroup() %>%
  select(-group1, -group2)

#   c1    c2      N   dep
#  <chr> <chr> <int> <int>
#1 a     b        30    20
#2 a     c         5     0
#3 a     d        10    10
#4 c     a         5     0
#5 b     a        10    20
</code>```

Body:
A data frame is given and the objective is to calculate the direct dependency value between two columns of the data frame.

c1  c2   N
a    b   30
a    c   5
a    d   10
c    a   5
b    a   10

what we are looking for is that to get the direct dependency relations, for example, for aand b this value is ab - ba = 20.
The final result should be like this:

c1  c2   N     DepValue
a    b   30    ab - ba = 20
a    c   5     ac - ca = 0
a    d   10    ad- 0 = 10
c    a   5     ca - ac= 0
b    a   10    ba - ab = 20

Thank you for your help.

Body:
One option is to create groups with pmin and pmax values of c1 and c2 and take difference between the two values. This will return NA for groups with only one value, we can replace those NAs to the first value in the group.

library(dplyr)

df %>%
  group_by(group1 = pmin(c1, c2), group2 = pmax(c1, c2)) %>%
  mutate(dep = N[1] - N[2],
         dep = replace(dep, is.na(dep), N[1])) %>%
  ungroup() %>%
  select(-group1, -group2)

#   c1    c2      N   dep
#  <chr> <chr> <int> <int>
#1 a     b        30    20
#2 a     c         5     0
#3 a     d        10    10
#4 c     a         5     0
#5 b     a        10    20


来源: stackexchange

问:
How to update document key in mongodb using update command?
I tried to insert data into mongodb.its sucessfully inserted but I facing issue wrong document insert into mongodb.how to update both key and value in document using update query in mongodb.

Json Data format

```<code>{
             "brand": "LG",
             "colour": "Black",
             "item height": "14 Millimeters",
             "item width": "14.1 Centimeters",
             "item weight": "200 g",
             "product dimensions": "13.5 x 14.1 x 1.4 cm",
             "item model number": "GP65NB60",
             "included components": "Power2Go, PowerBackup, YouCam, LabelPrint and Norton internet security (60 days trial)"
}
</code>```

How to update key ex brand to brands using update query in mongodb.

答:
You can use $rename operator to update the key as

```<code>db.collectionName.update( { _id: 1 }, { $rename: { 'brand': 'brands'} } )
</code>```

and to update the values, use $set operator,

```<code>db.collectionName.update(
   { _id: 100 },
   { $set:
      {
        key1: value1,
        key2: value2,
        .....
      }
   }
)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I tried to insert data into mongodb.its sucessfully inserted but I facing issue wrong document insert into mongodb.how to update both key and value in document using update query in mongodb.

Json Data format

{
             "brand": "LG",
             "colour": "Black",
             "item height": "14 Millimeters",
             "item width": "14.1 Centimeters",
             "item weight": "200 g",
             "product dimensions": "13.5 x 14.1 x 1.4 cm",
             "item model number": "GP65NB60",
             "included components": "Power2Go, PowerBackup, YouCam, LabelPrint and Norton internet security (60 days trial)"
}

How to update key ex brand to brands using update query in mongodb.

Body:
You can use $rename operator to update the key as

db.collectionName.update( { _id: 1 }, { $rename: { 'brand': 'brands'} } )

and to update the values, use $set operator,

db.collectionName.update(
   { _id: 100 },
   { $set:
      {
        key1: value1,
        key2: value2,
        .....
      }
   }
)


问:
Unable to create a folder inside .zip file after reading the file data from list of attachments
I am reading list of attachment files and then creating a zip file. Inside the zip file i am creating a folder with a name of 'Attachments' and storing all the attachments files. The following code used is for creating zip file with 'Attachment folder'. I have debugged and found that inside myBlob variable the data is present, the zip file is generated but the 'Attachment folder' is not there. Can someone tell me how to do it?</p>

```<code>for (let i = 0; i < attachmentList.length; i++) {
  const attachment = attachmentList[i]
  const xhr = new XMLHttpRequest()
  xhr.open('GET', attachment.url, true)
  xhr.responseType = 'blob'
  xhr.onload = function(e) {
    if (this.status === 200) {
      const myBlob = this.response
      zip.file(`Attachments/${fileName}`, myBlob)
    }
  }
  xhr.send()
}
</code>```

答:
```<code>const data = fetch(url)
            .then((response) => {
                return response.blob()
            })
            zip.file(`Attachments/${fileName}`, data)
</code>```

Body:
I am reading list of attachment files and then creating a zip file. Inside the zip file i am creating a folder with a name of 'Attachments' and storing all the attachments files. The following code used is for creating zip file with 'Attachment folder'. I have debugged and found that inside myBlob variable the data is present, the zip file is generated but the 'Attachment folder' is not there. Can someone tell me how to do it?

for (let i = 0; i < attachmentList.length; i++) {
  const attachment = attachmentList[i]
  const xhr = new XMLHttpRequest()
  xhr.open('GET', attachment.url, true)
  xhr.responseType = 'blob'
  xhr.onload = function(e) {
    if (this.status === 200) {
      const myBlob = this.response
      zip.file(`Attachments/${fileName}`, myBlob)
    }
  }
  xhr.send()
}


问:
How do I retrieve the id of the selected option from a bootstrap dropDown list?
I have built this simple dropDown list:

Here's its html definition:

```<code><select class="form-control" id='0' (change)="retrieveValue($event.target)">
      <option id='0'>{{ genericSpecific[params.node.id][0] }}</option>
      <option id='1'>{{ genericSpecific[params.node.id][1] }}</option>
    </select>
</code>```

For retrieving the value:

```<code>  updateChosenValue(event) {
 console.log(event.value)}
</code>```

But, I couldn't find a way to retrieve the id.

Any help?

Thank you!

答:
Try this. this may help you to understand the logic.. but still you'll have to make this compatible to your angular code.

    <select onchange="alert(this.options[this.selectedIndex].getAttribute('id'));" name="myname" class="myclass">
        <option id="1" value="hi">click1</option>
        <option id="2" value="hello">click2</option>
    </select>```

Body:
I have built this simple dropDown list:

Here's its html definition:

<select class="form-control" id='0' (change)="retrieveValue($event.target)">
      <option id='0'>{{ genericSpecific[params.node.id][0] }}</option>
      <option id='1'>{{ genericSpecific[params.node.id][1] }}</option>
    </select>

For retrieving the value:

  updateChosenValue(event) {
 console.log(event.value)}

But, I couldn't find a way to retrieve the id.

Any help?

Thank you!


问:
Performance: Double nested subquery unknown column
If I do COUNT()/AVG() in the first subquery MySQL process all rows inside the table, because of that reason it is necessary to filter at from all rows with another subquery.

As example if I have 3 rows, but only 1 row has the id which should get count, MySQL process all 3 rows (according to EXPLAIN) and does the where clause after.

If I'm able to select in a double nested sub query this single row and call the count outside it would be a lot better performance wise.

The problem MySQL does not allow using outer values in a second level subquery.

Simple example of my code:

```<code>SELECT
    pr.id, pr.catid, ...
    (
        SELECT COUNT(pra.id)
        FROM (
            SELECT id
            FROM productsrating
            WHERE pr.id = productid
        ) pra
    ) as ratingcount,
    ...
FROM
(
    SELECT id, ...
    FROM products
    WHERE active = 1

) pr
</code>```

-> Unknown column pr.id

I do also tried to use the COUNT in the main select but it isn't allowed to have multiple values inside a subquery.

Edit: I have an index on productid.

EDIT2 SOLUTION:
Sorry at all its working fine with the first single subquery, server problems caused bad behavior.

答:
Try count with distinct </p>

```<code>SELECT
    pr.id, pr.catid, ...
    (
        SELECT COUNT(Distinct productsrating.id)
        FROM productsrating
        WHERE pr.id = productid
    ) as ratingcount,
    ...
FROM
(
    SELECT id, ...
    FROM products
    WHERE active = 1

) pr
</code>```

Body:
If I do COUNT()/AVG() in the first subquery MySQL process all rows inside the table, because of that reason it is necessary to filter at from all rows with another subquery.

As example if I have 3 rows, but only 1 row has the id which should get count, MySQL process all 3 rows (according to EXPLAIN) and does the where clause after.

If I'm able to select in a double nested sub query this single row and call the count outside it would be a lot better performance wise.

The problem MySQL does not allow using outer values in a second level subquery.

Simple example of my code:

SELECT
    pr.id, pr.catid, ...
    (
        SELECT COUNT(pra.id)
        FROM (
            SELECT id
            FROM productsrating
            WHERE pr.id = productid
        ) pra
    ) as ratingcount,
    ...
FROM
(
    SELECT id, ...
    FROM products
    WHERE active = 1

) pr

-> Unknown column pr.id

I do also tried to use the COUNT in the main select but it isn't allowed to have multiple values inside a subquery.

Edit: I have an index on productid.

EDIT2 SOLUTION:
Sorry at all its working fine with the first single subquery, server problems caused bad behavior.

Body:
Try count with distinct

SELECT
    pr.id, pr.catid, ...
    (
        SELECT COUNT(Distinct productsrating.id)
        FROM productsrating
        WHERE pr.id = productid
    ) as ratingcount,
    ...
FROM
(
    SELECT id, ...
    FROM products
    WHERE active = 1

) pr


问:
Python app to make a random prime number between 10^300 and 10^301
i need to make Python app to make a random prime number between 10^300 and 10^301 , i done it with this but its very slow. any solution?

```<code>
import random , math
check_prime = 0</p>

<p>print "Please wait ..."
def is_prime(n):
    import math
    n = abs(n)
    i = 2
    while i <= math.sqrt(n):
        if n % i == 0:
            return False
        i += 1<br>
    return True</p>

<p>while check_prime == 0 :
    randomnumber = random.randrange(math.pow(10,300),math.pow(10,301)-1)
    if is_prime(randomnumber):
        print randomnumber
        break
```

答:
As explained in the comments, you can forget about building a list of all primes between 10^300 and 10^301 and picking one randomly - there's orders of magnitudes too many primes in that range for that to work.

The only practical approach, as far as I can see, is to randomly pick a number from the range, then test if it is prime. Repeat until you find a prime.

For the primality testing, that's a whole subject by itself (libraries [in the book sense] have been written about it). Basically you first do a few quick tests to discard numbers that are obviously not prime, then you bring out the big guns and use one of the common primality tests (Miller-Rabin (iterated), AKS, ...).  I don't know enough to recommend one, but that's really a topic for research-level maths, so you should probably head over to https://math.stackexchange.com/ .

See e.g. this question for a starting point and some simple recipes:

How do you determine if a number is prime or composite?

About your code:

The code you post basically does just what I described, however it uses an extremely naive primality test (trial division by all numbers 1...sqrt(n)). That's why it's so slow. If you use a better primatlity test, it will be orders of magnitude faster.

ContentLicense: CC BY-SA 3.0

Body:
i need to make Python app to make a random prime number between 10^300 and 10^301 , i done it with this but its very slow. any solution?

import random , math
check_prime = 0

print "Please wait ..."
def is_prime(n):
    import math
    n = abs(n)
    i = 2
    while i <= math.sqrt(n):
        if n % i == 0:
            return False
        i += 1

    return True

while check_prime == 0 :
    randomnumber = random.randrange(math.pow(10,300),math.pow(10,301)-1)
    if is_prime(randomnumber):
        print randomnumber
        break


问:
Converting from alpha to numeric with decimals fails
I have to convert a alphanumeric value  to a numeric value with decimal places:

Input: '6000'

Output. 60.00

So I tried the %dec() BIF which takes the input as alpha, the precision and the decimal places. But when trying this:

```<code>dcl-s alphanumeric char(13);
dcl-s numeric packed(13:2);

alphanumeric = '6000';
numeric = %dec(alphanumeric:13:2);

*inlr = *on;
</code>```

the conversion produces NUMERIC = 00000006000.00 and not NUMERIC = 000000060.00. So what am I doing wrong?

Even when using zoned(13:2) instead of packed(13:2) the value doesn't have decimal places other than '00'

答:
The only easy way i know is a mix from free with good old rpg-syntax:

  EvalR VarText = '6000';
C                   Move      VarText       VarDec```

With move you can easily transfer the right adjusted value into the numeric field

Body:
I have to convert a alphanumeric value  to a numeric value with decimal places:

Input: '6000'

Output. 60.00

So I tried the %dec() BIF which takes the input as alpha, the precision and the decimal places. But when trying this:

dcl-s alphanumeric char(13);
dcl-s numeric packed(13:2);

alphanumeric = '6000';
numeric = %dec(alphanumeric:13:2);

*inlr = *on;

the conversion produces NUMERIC = 00000006000.00 and not NUMERIC = 000000060.00. So what am I doing wrong?

Even when using zoned(13:2) instead of packed(13:2) the value doesn't have decimal places other than '00'

Body:
The only easy way i know is a mix from free with good old rpg-syntax:

  EvalR VarText = '6000';
C                   Move      VarText       VarDec

With move you can easily transfer the right adjusted value into the numeric field


问:
File Transfer via Internet ( using java)
I've a java(swing) application running on server and client(or assume two different

computers),These two are connected through Internet not by LAN or WAN..The client has to send

some data (around 200 kb) to the server.Which method is preferable for transferring data..I used

TCP through LAN,but it's working slow through Internet..So can I use UDP for internet ?  If yes, I don't

know how to divide my data into chunks and send it & again re-assemble the data at the server.

I am really thankful if source code is provided for UDP transfer(bulk data in java).

thanks in advance..

答:
Use TCP, it does exactly what you want in a way which is much better than you can hope to implement on your own. If you have low bandwidth, transfer in the background or just wait - there is nothing you can do with that.

Read your data in byte arrays and write them as a whole - see DataInputStream.readFully(). Flush the output at the end of the writing.

Edit:If you want to send multiple images, one after the other, you can do video compression - it is designed to be efficient just at that.


问:
How can i display a particular product?
I am trying to display a particular product by clicking on it from the list

```<code><ul>
    <% products.each do |product| %>
    <tr>

        <a href="<%= products_path(@product) %>"><%= product.title %> .   </a>
        <br/>

    </tr>
    <% end %>
</ul>
</code>```

Expected results should be products/1 but the result is products.1 and should displays a list of products

答:
If your routes used resources :products , then you can use simply

No need to use any path. Just go with Product object.

Note : In controller method should be call "show".

Title: How can i display a particular product?

Body:
I am trying to display a particular product by clicking on it from the list

    <% products.each do |product| %>

        <a href="<%= products_path(@product) %>"><%= product.title %> .

    <% end %>

Expected results should be products/1 but the result is products.1 and should displays a list of products


问:
How to delete duplicate records from Hive table?
I am trying to learn about deleting duplicate records from a Hive table.

My Hive table: 'dynpart' with columns: Id, Name, Technology

```<code>Id  Name  Technology
1   Abcd  Hadoop
2   Efgh  Java
3   Ijkl  MainFrames
2   Efgh  Java
</code>```

We have options like 'Distinct' to use in a select query, but a select query just retrieves data from the table. Could anyone tell how to use a delete query to remove the duplicate rows from a Hive table.

Sure that it is not recommended or not the standard to Delete/Update records in Hive. But I want to learn how do we do it.

答:
Just in case when your table has duplicate rows on few or selected columns. Suppose you have a table structure as shown down below:

```<code>id  Name    Technology
1   Abcd    Hadoop
2   Efgh    Java       --> Duplicate
3   Ijkl    Mainframe
2   Efgh    Python     --> Duplicate
</code>```

Here id & Name columns having duplicate rows.
You can use analytical function to get the duplicate row as:

```<code>select * from
(select Id,Name,Technology,
row_Number() over (partition By Id,Name order by id desc) as row_num
from yourtable)tab
where row_num > 1;
</code>```

This will give you output as:

```<code>id  Name    Technology  row_num
2   Efgh    Python           2
</code>```

When you need to get both the duplicate rows:

```<code>select * from
(select Id,Name,Technology,
count(*) over (partition By Id,Name order by id desc) as duplicate_count
from yourtable)tab
where duplicate_count> 1;
</code>```

Output as:

```<code>id  Name    Technology  duplicate_count
2   Efgh    Java             2
2   Efgh    Python           2
</code>```

Body:
I am trying to learn about deleting duplicate records from a Hive table.

My Hive table: 'dynpart' with columns: Id, Name, Technology

Id  Name  Technology
1   Abcd  Hadoop
2   Efgh  Java
3   Ijkl  MainFrames
2   Efgh  Java

We have options like 'Distinct' to use in a select query, but a select query just retrieves data from the table. Could anyone tell how to use a delete query to remove the duplicate rows from a Hive table.

Sure that it is not recommended or not the standard to Delete/Update records in Hive. But I want to learn how do we do it.

Body:
Just in case when your table has duplicate rows on few or selected columns. Suppose you have a table structure as shown down below:

id  Name    Technology
1   Abcd    Hadoop
2   Efgh    Java       --> Duplicate
3   Ijkl    Mainframe
2   Efgh    Python     --> Duplicate

Here id & Name columns having duplicate rows.
You can use analytical function to get the duplicate row as:

select * from
(select Id,Name,Technology,
row_Number() over (partition By Id,Name order by id desc) as row_num
from yourtable)tab
where row_num > 1;

This will give you output as:

id  Name    Technology  row_num
2   Efgh    Python           2

When you need to get both the duplicate rows:

select * from
(select Id,Name,Technology,
count(*) over (partition By Id,Name order by id desc) as duplicate_count
from yourtable)tab
where duplicate_count> 1;

Output as:

id  Name    Technology  duplicate_count
2   Efgh    Java             2
2   Efgh    Python           2


答:
try this

```<code><select class="form-control" id='0' (change)="retrieveValue($event.target)">
  <option  id='0' value='0'>{{ genericSpecific[params.node.id][0] }}</option>
  <option id='1' value='1'>{{ genericSpecific[params.node.id][1] }}</option>
</select>
</code>```

https://stackblitz.com/edit/angular-vo9cuj

Title: How do I retrieve the id of the selected option from a bootstrap dropDown list?

Body:
try this

<select class="form-control" id='0' (change)="retrieveValue($event.target)">
  <option  id='0' value='0'>{{ genericSpecific[params.node.id][0] }}</option>
  <option id='1' value='1'>{{ genericSpecific[params.node.id][1] }}</option>
</select>

https://stackblitz.com/edit/angular-vo9cuj


问:
Sorted Permutation Rank with Repeats
Given a string, find the rank of the string amongst its permutations sorted lexicographically.
Note that the characters might be repeated. If the characters are repeated, we need to look at the rank in unique permutations.

Look at the example for more details.

Input : 'aba'

Output : 2

The order permutations with letters 'a', 'a', and 'b' :

aab

aba

baa

I was able to solve for unique characters but not with repeated characters. Can someone help me code this in python?

Thanks

答:
```<code>long long int pow_mod(long long int a,long long int b)
{
    long long MOD=1000003;
    if(a == 1)
    return 1;
    long long int x =1 ,y = a;
    while(b>0)
    {
        if(b%2)
        {
            x = (x*y)%MOD;
        }
        y = (y*y)%MOD;
        b = b>>1;
    }
    return x;
}

int Solution::findRank(string A) {
    long long ans=0;
    long long mod=1000003;
    long long  arr[300];
    long long n=A.length();
    long long fact[n];
    fact[0]=1;
    for(int i=1;i<n;i++)
    {
        fact[i]=((fact[i-1]%mod)*(i%mod))%mod;
    }
    for(long long i=0;i<300;i++)
        arr[i]=0;

    for(long long i=0;i<n;i++)
    {

        arr[A[i]]++;

    }
   // for(long long i=0;i<26;i++)
     //   cout<<arr[i]<<" ";

    for(long long i=0;i<n;i++)
    {

        long long cnt=0;
        long long di=1;

        for(long long j=(A[i]-1);j>=0;j--)
        {
                        cnt+=arr[j];

        }

       // cout<<cnt<<" ";

        for(int j=0;j<300;j++)
        {

            di=(di%mod * fact[arr[j]]%mod)%mod;
        }
        long long a=pow_mod(di,(mod - 2)) % mod;

       // cout<<di<<" ";

        ans=(ans+((cnt*fact[n-i-1])%mod * a )%mod)%mod;

      //  cout<<ans<<" ";
       arr[A[i]]--;

    }
    ++ans;
    return ans%mod;

}
</code>```

Title: Sorted Permutation Rank with Repeats


问:
SMTPRecipientsRefused in django
when i am trying to send mails through django I am getting the above error .
Can you please tell the cause of this error and how to avoid it?</p>

答: Your mail server isn't allowed to send mail. The likelyhood of this having anything to do with Django is small. Check your mailserver settings and whether your provider will allow you sending mail.</p>

Title: SMTPRecipientsRefused in django


问:
Getting exception "openpyxl.utils.exceptions.IllegalCharacterError"
I am extracting data from an Oracle 11g Database using python and writing it to an Excel file. During extraction, I'm using a python list of tuples (each tuple indicates each row in dataset) and the openpyxl module to write the data into Excel. It's working fine for some datasets but for some, it's throwing the exception:

openpyxl.utils.exceptions.IllegalCharacterError

This is the solution I've already tried:

Openpyxl.utils.exceptions.IllegalcharacterError

Here is my Code:

for i in range(0,len(list)):
    for j in range(0,len(header)):
        worksheet_ntn.cell(row = i+2, column = j+1).value = list[i][j]
```

<p>Here is the error message:</p>

```    raise IllegalCharacterError
openpyxl.utils.exceptions.IllegalCharacterError
```

答: The exception tells you everything you need to know: you must replace the characters that cause the exception. This can be done using re.sub() but, seeing as only you can decide what you want to replace them with — spaces, empty strings, etc. — only you can do this.

Body:
I am extracting data from an Oracle 11g Database using python and writing it to an Excel file. During extraction, I'm using a python list of tuples (each tuple indicates each row in dataset) and the openpyxl module to write the data into Excel. It's working fine for some datasets but for some, it's throwing the exception:

openpyxl.utils.exceptions.IllegalCharacterError

This is the solution I've already tried:

Openpyxl.utils.exceptions.IllegalcharacterError

Here is my Code:

for i in range(0,len(list)):
    for j in range(0,len(header)):
        worksheet_ntn.cell(row = i+2, column = j+1).value = list[i][j]

Here is the error message:

    raise IllegalCharacterError
openpyxl.utils.exceptions.IllegalCharacterError


问:
Java best practices static final map values
I have a utility class which contains a static final map with some values. I need to access to this map in another class. Should I just declare the map as public, or should I write a getter inside the utility class, and therefore let the map be private?

Both ways work, but what are the best practices?

```<code>public MyUtilityClass {
  public static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
      "title", 256,
      "text", 512);

}

public MyAnotherClass {

  public void someMethod() {
    //accessing the map directly
    MAX_LENGTHS.get("title")
  }

}
</code>```

Or

```<code>public MyUtilityClass {
  private static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
      "title", 256,
      "text", 512);

  public static final getMaxLengthMap() {return MAX_LENGTHS;}
}

public MyAnotherClass {
  public void someMethod() {
    //accessing the map directly
    getMaxLengthMap().get("title")
  }
}
</code>```

Well, actually the keys are enum values.
Something like :

```<code>private static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
      MyEnumClass.TITLE, 256,
      MyEnumClass.TEXT, 512);
</code>```

答:
I think adding a getter to the owning class would be the way to go.

```<code>public MyUtilityClass {
  private static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
      "title", 256,
      "text", 512);

  public static int getLength(final String key) {
     return MAX_LENGTHS.get(key);
  }
}

public MyAnotherClass {
  public void someMethod() {

    int x= MyUtilityClass.getLength("title")
  }
}
</code>```

This insulates MyAnotherClass from needing to know any implementation details of the getter and makes mocking for testing much easier.

Body:
I have a utility class which contains a static final map with some values. I need to access to this map in another class. Should I just declare the map as public, or should I write a getter inside the utility class, and therefore let the map be private?

Both ways work, but what are the best practices?

public MyUtilityClass {
  public static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
      "title", 256,
      "text", 512);

}

public MyAnotherClass {

  public void someMethod() {
    //accessing the map directly
    MAX_LENGTHS.get("title")
  }

}

Or

public MyUtilityClass {
  private static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
      "title", 256,
      "text", 512);

  public static final getMaxLengthMap() {return MAX_LENGTHS;}
}

public MyAnotherClass {
  public void someMethod() {
    //accessing the map directly
    getMaxLengthMap().get("title")
  }
}

Well, actually the keys are enum values.
Something like :

private static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
      MyEnumClass.TITLE, 256,
      MyEnumClass.TEXT, 512);

Body:
I think adding a getter to the owning class would be the way to go.

public MyUtilityClass {
  private static final Map<String, Integer> MAX_LENGTHS = ImmutableMap.of(
      "title", 256,
      "text", 512);

  public static int getLength(final String key) {
     return MAX_LENGTHS.get(key);
  }
}

public MyAnotherClass {
  public void someMethod() {

    int x= MyUtilityClass.getLength("title")
  }
}

This insulates MyAnotherClass from needing to know any implementation details of the getter and makes mocking for testing much easier.


答:
Change HTML

```<code><select class="form-control" id='0' (change)="retrieveValue($event)">
      <option id='0'>A</option>
      <option id='1'>B</option>
    </select>
</code>```

Update ts

```<code>retrieveValue(event) {
     const selectEl = event.target;
     const val = selectEl.options[selectEl.selectedIndex].getAttribute('id');
     console.log(val)
 }
</code>```

https://stackblitz.com/edit/angular-yfb45a

Body:
Change HTML

<select class="form-control" id='0' (change)="retrieveValue($event)">
      <option id='0'>A</option>
      <option id='1'>B</option>
    </select>

Update ts

retrieveValue(event) {
     const selectEl = event.target;
     const val = selectEl.options[selectEl.selectedIndex].getAttribute('id');
     console.log(val)
 }

https://stackblitz.com/edit/angular-yfb45a


问:
Split string and take last element
I have a table with this values:

```<code>Articles/Search/ArtMID/2681/ArticleID/2218/Diet.aspx
OurStory/MeettheFoodieandtheMD.aspx
TheFood/OurMenu.aspx
</code>```

I want to get this

```<code>Diet.aspx
MeettheFoodieandtheMD.aspx
OurMenu.aspx
</code>```

How can i do this?

答:
```<code>reverse(SUBSTRING(reverse(yourString),0,CHARINDEX('/',reverse(yourString)))) as stringLastPart
</code>```

Title: Split string and take last element

Body:
I have a table with this values:

Articles/Search/ArtMID/2681/ArticleID/2218/Diet.aspx
OurStory/MeettheFoodieandtheMD.aspx
TheFood/OurMenu.aspx

I want to get this

Diet.aspx
MeettheFoodieandtheMD.aspx
OurMenu.aspx

How can i do this?


问:
Automatic change of web.config under source control during CI build
I am working with couple of friends on an ASP.NET MVC website. The project is maintained in SVN and I have CC.Net set up to checkout latest version and do automated build and deploy to a pre-production server. The default build configuration is set to Debug, but the automated build is set to build Retail. Everything works just fine, except for the <compilation debug=""> in web.config which currently is set always to true. I'd like to be able to specify true or false for <compilation debug=""> based on the build flavor.

I've thought about two separate solutions to this problem.

I could have a pre/post-build step that modifies the value. However, the web.config file is under source control, so modifying it in the automated build will leave it checked out on the build machine. I could also have additional step that would revert it as well.

I could also instead of having web.config under source control, have a web.config.base file that is used as a source during the build to generate the web.config file. The problem with this approach is that most of the tools modify web.config directly and we have to manually merge such changes back in the base file. And since there's no indication when any tool changed web.config, we have to look for changes at any checkin. Not only this becomes a tedious manual step, but it's also error prone.

Both of these approaches would work, but have some shortcomings. I was hoping there's a more elegant way of doing this. Thus the question - how do you guys deal with modifying web.config that is under source control during the CI builds?

答:
we have a

web.config for development

web.config.cert which is deployed by hudson to our cert environment

web.config.prod which is used for production

This allows us to put comments in there and values in there specific to the environments when that would normally have to go in some documentation somewhere, and it would surely be ignored.

Like I said, we have Hudson deploy to our cert environment on each build, so it just copies the directory over, deletes the web.config and renames web.config.cert to web.config

You may want to check out Hudson, I dont think I've ever heard of anyone choosing CC.net over Hudson if they had the ability to choose :)

OwnerDisplayName: Franci Penov

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Allen


问:
Displaying custom local image marker in OSM using OpenLayers
I have followed the tutorial on how to display a custom image as a marker from this article: https://medium.com/attentive-ai/working-with-openlayers-4-part-3-setting-customised-markers-and-images-on-map-da3369a81941

However, when using my own local project structure to reference my png image, it does not get rendered on the map.

Here is my current code:

var aPoint = new ol.geom.Point(ol.proj.fromLonLat([0, 0]))
var aFeature = new ol.Feature({
  geometry: aPoint
})
var aFeatureStyle = new ol.style.Style({
  image: new ol.style.Icon({
    //src: 'https://upload.wikimedia.org/wikipedia/commons/2/2a/Dot.png'
    src: '../../../dott.png'
  })
})
aFeature.setStyle(aFeatureStyle)
var aSource = new ol.source.Vector({
  features: [aFeature]
})
var aLayer = new ol.layer.Vector({
  source: aSource
})

var map = new ol.Map({
    target: 'map',
    layers: [
        new ol.layer.Tile({
            source: new ol.source.OSM(),
        }),
        aLayer
    ],
    view: new ol.View({
        center: ol.proj.fromLonLat([0, 0]),
        zoom: 14
    })
})
```

When using the src: 'https://upload.wikimedia.org/wikipedia/commons/2/2a/Dot.png' variant, the required dot gets displayed, but when using
src: '../../../dott.png' no markers are displayed.

I have definitely specified the right path to my local png file, so I am out of ideas why this code doesn't work.

I am using the Angular framework and running this on a local development server using Node.

答:
So I finally figured it out, and I feel like I should've known this earlier, but since I'm new to Angular I didn't spot it straight away.

Any images that are needed to be referenced in source code in Angular need to be in src/assets/images folder in the Angular project structure. Then by specifying the path as src: '../assets/images/Dot.png' the image is successfully loaded with a 200 OK response, seen in the Network tab of a browser's Developer Tools.

Body:
I have followed the tutorial on how to display a custom image as a marker from this article: https://medium.com/attentive-ai/working-with-openlayers-4-part-3-setting-customised-markers-and-images-on-map-da3369a81941

However, when using my own local project structure to reference my png image, it does not get rendered on the map.

Here is my current code:

var aPoint = new ol.geom.Point(ol.proj.fromLonLat([0, 0]))
var aFeature = new ol.Feature({
  geometry: aPoint
})
var aFeatureStyle = new ol.style.Style({
  image: new ol.style.Icon({
    //src: 'https://upload.wikimedia.org/wikipedia/commons/2/2a/Dot.png'
    src: '../../../dott.png'
  })
})
aFeature.setStyle(aFeatureStyle)
var aSource = new ol.source.Vector({
  features: [aFeature]
})
var aLayer = new ol.layer.Vector({
  source: aSource
})

var map = new ol.Map({
    target: 'map',
    layers: [
        new ol.layer.Tile({
            source: new ol.source.OSM(),
        }),
        aLayer
    ],
    view: new ol.View({
        center: ol.proj.fromLonLat([0, 0]),
        zoom: 14
    })
})

When using the src: 'https://upload.wikimedia.org/wikipedia/commons/2/2a/Dot.png' variant, the required dot gets displayed, but when using
src: '../../../dott.png' no markers are displayed.

I have definitely specified the right path to my local png file, so I am out of ideas why this code doesn't work.

I am using the Angular framework and running this on a local development server using Node.


问:
I want to implement a tree-based regression model using rss
1.2 RSS
As stated in chapter 8 of the textbook, we need a parameter to measure the eﬃciency of a speciﬁc split/tree. We choose here Residual Sum of Squares. Implement RSS calculation for the list of splits, knowing that the value to predict (Wage(k)) is contained in element[-1] for element in split.
You can use the cell of code below your implementation to check your result on a speciﬁc split.

1.3 Split
We will code a split function capable of splitting the data in two part based on the index of the feature, the value of splitting and the data. Implement the condition of splitting, taking as convention left

1.4 Optimal split creation
There is no theoritecal result allowing to ﬁnd the best possible split before going through all the possible one, so we implement a RSS minimizer over the whole split. Using previously coded functions, ﬁll the #TODO parts. You can check your return in the following cell.

1.5 Tree Building and prediction
Aggregating all the parts of the code now allows us to build the whole tree recursively. Comment the given code, and especially the importance of the parameter min_size in regard to the model structure
Using the same coding paradigm allows us to use our model to do regression on the test set, as you can see in the next cell of code. Which part of the global model is now missing ? Explain its importance in a real machine learning problem. (Bonus) Implement it

I want to implement a tree-based regression model using rss. I want to fill out the following blanks but it is too difficult

```<code>import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import math

data = pd.read_csv("Wages.csv", sep=";")

training_set = np.array(data[:10])
test_set = np.array(data[10:])

-- RSS --

verbose = False
def RSS(splits):
    """
    Return the RSS of the input splits. The input should be in the form
of a list of list
    """
    residual = 0
    for split in splits:
        if(len(split) != 0):
            mean = mean(split[:-1])
            if(verbose):print("Mean :" + str(mean))
            residual = ##TODO
    return residual

split_1 = np.array([[[0,2],[0,8]],[[4,5]]])
RSS_value = RSS(split_1)
if (type(RSS_value) not in [int,float,np.float16,np.float32,np.float64]):
    print("TypeError : check your output")
elif(RSS(split_1) == 18.0):
    print("Your calculations are right, at least on this specific
example")
else:
    print("Your calculations are wrong")

-- Split --

def split(index, value, data):
    """
    Splits the input @data into two parts, based on the feature at @index
position, using @value as a boundary value
    """
    left_split = #TODO condition
    right_split = #TODO condition
    return [left_split, right_split]

-- optimal split creation

def split_tester(data):
    """
    Find the best possible split possible for the current @data.
    Loops over all the possible features, and all values for the given
features to test every possible split
    """
optimal_split_ind, optimal_split_value, optimal_residual, optimal_splits = -1,-1,float("inf"),[] #Initialize such that the first split is better than initialization
for curr_ind in range(data.shape[1]-1):
    for curr_val in data:
        if(verbose):print("Curr_split : " + str((curr_ind, curr_val[curr_ind])))
        split_res = #TODO (comments : get the current split)

        if(verbose):print(split_res)
        residual_value = #TODO (comments : get the RSS of the current split)

        if(verbose):print("Residual : " + str(residual_value))
        if residual_value < optimal_residual:
            optimal_split_ind, optimal_split_value, optimal_residual, optimal_splits = curr_ind,\
                                                                curr_val[curr_ind], residual_value, split_res

return optimal_split_ind, optimal_split_value, optimal_splits

-- tree building --

def tree_building(data, min_size):
    """
    Recursively builds a tree using the split tester built before.
    """
    if(data.shape[0] > min_size):
        ind, value, [left, right] = split_tester(data)
        left, right = np.array(left), np.array(right)
        return [tree_building(left, min_size), tree_building(right,
min_size),ind,value]
    else:
        return data

tree = tree_building(training_set,2)

def predict(tree, input_vector):
    if(type(tree[-1]) != np.int64):
        if(len(tree) == 1):
            return(tree[0][-1])
        else:
            return(np.mean([element[-1] for element in tree]))
    else:
        left_tree, right_tree, split_ind, split_value = tree
        if(input_vector[split_ind]<split_value):
            return predict(left_tree, input_vector)
        else:
            return predict(right_tree, input_vector)

for employee in test_set:
    print("Predicted : " + str(predict(tree,employee)) + ", Actual : " +
str(employee[-1]))
</code>```

I'm studying the code to get #TODO here. I do not know. Please help me.

答: If I understand correctly, you are only asking for the calculation marked #TODO in the code you posted. If you calculate the errors predicted by your model, these error values are sometimes called the "residual errors". You cannot simply sum these, some are negative and some are positive so they might cancel each other. However, if the errors are all squared, then the squared errors are all positive values and can be summed. This is where the term "Residual Sum of Squares" (RSS) comes from. You can use something like "RSS = numpy.sum(numpy.square(errors))" to calculate this value.</p>

Body:
1.2 RSS
As stated in chapter 8 of the textbook, we need a parameter to measure the eﬃciency of a speciﬁc split/tree. We choose here Residual Sum of Squares. Implement RSS calculation for the list of splits, knowing that the value to predict (Wage(k)) is contained in element[-1] for element in split.
You can use the cell of code below your implementation to check your result on a speciﬁc split.

1.3 Split
We will code a split function capable of splitting the data in two part based on the index of the feature, the value of splitting and the data. Implement the condition of splitting, taking as convention left

1.4 Optimal split creation
There is no theoritecal result allowing to ﬁnd the best possible split before going through all the possible one, so we implement a RSS minimizer over the whole split. Using previously coded functions, ﬁll the #TODO parts. You can check your return in the following cell.

1.5 Tree Building and prediction
Aggregating all the parts of the code now allows us to build the whole tree recursively. Comment the given code, and especially the importance of the parameter min_size in regard to the model structure
Using the same coding paradigm allows us to use our model to do regression on the test set, as you can see in the next cell of code. Which part of the global model is now missing ? Explain its importance in a real machine learning problem. (Bonus) Implement it

I want to implement a tree-based regression model using rss. I want to fill out the following blanks but it is too difficult

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import math

data = pd.read_csv("Wages.csv", sep=";")

training_set = np.array(data[:10])
test_set = np.array(data[10:])

-- RSS --

verbose = False
def RSS(splits):
    """
    Return the RSS of the input splits. The input should be in the form
of a list of list
    """
    residual = 0
    for split in splits:
        if(len(split) != 0):
            mean = mean(split[:-1])
            if(verbose):print("Mean :" + str(mean))
            residual = ##TODO
    return residual

split_1 = np.array([[[0,2],[0,8]],[[4,5]]])
RSS_value = RSS(split_1)
if (type(RSS_value) not in [int,float,np.float16,np.float32,np.float64]):
    print("TypeError : check your output")
elif(RSS(split_1) == 18.0):
    print("Your calculations are right, at least on this specific
example")
else:
    print("Your calculations are wrong")

-- Split --

def split(index, value, data):
    """
    Splits the input @data into two parts, based on the feature at @index
position, using @value as a boundary value
    """
    left_split = #TODO condition
    right_split = #TODO condition
    return [left_split, right_split]

-- optimal split creation

def split_tester(data):
    """
    Find the best possible split possible for the current @data.
    Loops over all the possible features, and all values for the given
features to test every possible split
    """
optimal_split_ind, optimal_split_value, optimal_residual, optimal_splits = -1,-1,float("inf"),[] #Initialize such that the first split is better than initialization
for curr_ind in range(data.shape[1]-1):
    for curr_val in data:
        if(verbose):print("Curr_split : " + str((curr_ind, curr_val[curr_ind])))
        split_res = #TODO (comments : get the current split)

        if(verbose):print(split_res)
        residual_value = #TODO (comments : get the RSS of the current split)

        if(verbose):print("Residual : " + str(residual_value))
        if residual_value < optimal_residual:
            optimal_split_ind, optimal_split_value, optimal_residual, optimal_splits = curr_ind,\
                                                                curr_val[curr_ind], residual_value, split_res

return optimal_split_ind, optimal_split_value, optimal_splits

-- tree building --

def tree_building(data, min_size):
    """
    Recursively builds a tree using the split tester built before.
    """
    if(data.shape[0] > min_size):
        ind, value, [left, right] = split_tester(data)
        left, right = np.array(left), np.array(right)
        return [tree_building(left, min_size), tree_building(right,
min_size),ind,value]
    else:
        return data

tree = tree_building(training_set,2)

def predict(tree, input_vector):
    if(type(tree[-1]) != np.int64):
        if(len(tree) == 1):
            return(tree[0][-1])
        else:
            return(np.mean([element[-1] for element in tree]))
    else:
        left_tree, right_tree, split_ind, split_value = tree
        if(input_vector[split_ind]<split_value):
            return predict(left_tree, input_vector)
        else:
            return predict(right_tree, input_vector)

for employee in test_set:
    print("Predicted : " + str(predict(tree,employee)) + ", Actual : " +
str(employee[-1]))

I'm studying the code to get #TODO here. I do not know. Please help me.


问:
Run-time error '1004': Method 'Range' of object '_Worksheet' failed after saving the file
The code I'm trying to write should simply check the different price book entries in my companies system. It should take a purchase order from the past and check which would have been the cheapest price book entry for a specific minimum order quantety.
Before doing that the code defines a Range PBRange which then should be sorted to work with 'if' clauses afterwards.
When defining the PBRange the error 1004 occurs.

When I save and reopen the file a message pops up that there was a problem found with some content in the file. After asking me to recover it the code doesn't work anymore.
The strange thing is that the code worked perfectly fine in the beginning.

```<code>Public PBRange As Range
Public PO As Worksheet
Public PB As Worksheet

Sub CheapestPrice()

Dim LastRowPO As Long
Dim LastRowPB As Long

Dim i As Long
Dim j As Long

Set PO = Worksheets("Purchase Orders")
Set PB = Worksheets("Price Book")

'!!!Here the error occurs!!!
Set PBRange = PB.Range("A1", Range("A1").End(xlDown).End(xlToRight))
</code>```

The code after is just an if else combination with two for loops to work through the 2 worksheets. This should work perfeclty fine.

I expect a range to sort afterwards with different criteria.

答:
Referencing correctly is key to prevent errors. Even if they don't show up immediately, those errors will pop up and tackle your code sooner than later.

Correct referencing could be, for example:

```<code>Option Explicit

Public PBRange As Range
Public PO As Worksheet
Public PB As Worksheet

Sub CheapestPrice()
Dim LastRowPO As Long, LastRowPB As Long, i As Long, j As Long

Set PO = ThisWorkbook.Sheets("Purchase Orders")
Set PB = ThisWorkbook.Sheets("Price Book")

Set PBRange = PB.Range("A1", PB.Range("A1").End(xlDown).End(xlToRight))

End Sub
</code>```

In case you do not specify both the workbook and worksheet, like with Range("A1"), VBA will assume the active workbook and worksheet. If these are not what you intend to refer to, you will likely get an error. You could make your life easier by using a With...End With statement to prevent a lot of typing. E.g.:

```<code>Sub example()
Dim LRow As Long

With ThisWorkbook.Sheets(1)
    LRow = .Cells(.Rows.Count, "D").End(xlUp).Row
    MsgBox LRow

    .Range("D1:D" & LRow).Value = "NewValue"
End With

End Sub
</code>```

Body:
The code I'm trying to write should simply check the different price book entries in my companies system. It should take a purchase order from the past and check which would have been the cheapest price book entry for a specific minimum order quantety.
Before doing that the code defines a Range PBRange which then should be sorted to work with 'if' clauses afterwards.
When defining the PBRange the error 1004 occurs.

When I save and reopen the file a message pops up that there was a problem found with some content in the file. After asking me to recover it the code doesn't work anymore.
The strange thing is that the code worked perfectly fine in the beginning.

Public PBRange As Range
Public PO As Worksheet
Public PB As Worksheet

Sub CheapestPrice()

Dim LastRowPO As Long
Dim LastRowPB As Long

Dim i As Long
Dim j As Long

Set PO = Worksheets("Purchase Orders")
Set PB = Worksheets("Price Book")

'!!!Here the error occurs!!!
Set PBRange = PB.Range("A1", Range("A1").End(xlDown).End(xlToRight))

The code after is just an if else combination with two for loops to work through the 2 worksheets. This should work perfeclty fine.

I expect a range to sort afterwards with different criteria.

Body:
Referencing correctly is key to prevent errors. Even if they don't show up immediately, those errors will pop up and tackle your code sooner than later.

Correct referencing could be, for example:

Option Explicit

Public PBRange As Range
Public PO As Worksheet
Public PB As Worksheet

Sub CheapestPrice()
Dim LastRowPO As Long, LastRowPB As Long, i As Long, j As Long

Set PO = ThisWorkbook.Sheets("Purchase Orders")
Set PB = ThisWorkbook.Sheets("Price Book")

Set PBRange = PB.Range("A1", PB.Range("A1").End(xlDown).End(xlToRight))

End Sub

In case you do not specify both the workbook and worksheet, like with Range("A1"), VBA will assume the active workbook and worksheet. If these are not what you intend to refer to, you will likely get an error. You could make your life easier by using a With...End With statement to prevent a lot of typing. E.g.:

Sub example()
Dim LRow As Long

With ThisWorkbook.Sheets(1)
    LRow = .Cells(.Rows.Count, "D").End(xlUp).Row
    MsgBox LRow

    .Range("D1:D" & LRow).Value = "NewValue"
End With

End Sub


问:
AMP Form always showing submit-error, even on response code 200
I am using AMP form to send data to my Golang server. Even if I skip all handling of data sent and just write response with the code 200 as is said in AMP form reference, I still get shown the submit-error template.

This is my form (I skipped the fields because it would be too long)

```<code><form action-xhr="/contactus" method="POST" class="contactForm" target="_top" custom-validation-reporting="show-all-on-submit" id="contactForm">
    <fieldset>
        <!-- divs with input and submit button -->
    </fieldset>
    <div submit-success>
        <template type="amp-mustache">
            Success!
        </template>
    </div>
    <div submit-error>
        <template type="amp-mustache">
            Error!
        </template>
    </div>
</form>
</code>```

And this is an example of server response:

```<code>HTTP/1.1 200 OK
Content-Encoding: gzip
Vary: Accept-Encoding
Date: Sun, 23 Sep 2018 21:48:15 GMT
Content-Length: 23
Content-Type: application/x-gzip
</code>```

Could the problem be on server side?
I can't figure it out... Any idea is much appreciated

答:
Make sure that you implement AMP CORS headers.

Refer: https://amp.dev/documentation/guides-and-tutorials/learn/amp-caches-and-cors/amp-cors-requests?referrer=ampproject.org

If requests are for your own origin (your domain and not amp cached servers) then you can set following headers-

```<code>if (req.headers['amp-same-origin'] === 'true') {
    origin = req.query.__amp_source_origin;
    sourceOrigin = origin;
}

res.set({
    'Access-Control-Allow-Origin': origin,
    'AMP-Access-Control-Allow-Source-Origin': sourceOrigin,
    'Access-Control-Allow-Source-Origin': 'AMP-Access-Control-Allow-Source-Origin',
    'Access-Control-Expose-Headers': 'Access-Control-Allow-Origin' + ', AMP-Access-Control-Allow-Source-Origin' + ', Access-Control-Allow-Source-Origin'
});
</code>```

Body:
I am using AMP form to send data to my Golang server. Even if I skip all handling of data sent and just write response with the code 200 as is said in AMP form reference, I still get shown the submit-error template.

This is my form (I skipped the fields because it would be too long)

<form action-xhr="/contactus" method="POST" class="contactForm" target="_top" custom-validation-reporting="show-all-on-submit" id="contactForm">
    <fieldset>

    </fieldset>

        <template type="amp-mustache">
            Success!
        </template>

        <template type="amp-mustache">
            Error!
        </template>

</form>

And this is an example of server response:

HTTP/1.1 200 OK
Content-Encoding: gzip
Vary: Accept-Encoding
Date: Sun, 23 Sep 2018 21:48:15 GMT
Content-Length: 23
Content-Type: application/x-gzip

Could the problem be on server side?
I can't figure it out... Any idea is much appreciated

Body:
Make sure that you implement AMP CORS headers.

Refer: https://amp.dev/documentation/guides-and-tutorials/learn/amp-caches-and-cors/amp-cors-requests?referrer=ampproject.org

If requests are for your own origin (your domain and not amp cached servers) then you can set following headers-

if (req.headers['amp-same-origin'] === 'true') {
    origin = req.query.__amp_source_origin;
    sourceOrigin = origin;
}

res.set({
    'Access-Control-Allow-Origin': origin,
    'AMP-Access-Control-Allow-Source-Origin': sourceOrigin,
    'Access-Control-Allow-Source-Origin': 'AMP-Access-Control-Allow-Source-Origin',
    'Access-Control-Expose-Headers': 'Access-Control-Allow-Origin' + ', AMP-Access-Control-Allow-Source-Origin' + ', Access-Control-Allow-Source-Origin'
});


问:
Unable to create new folder using Desktop App using Electron JS
It works properly when I run the same code locally using Electron JS.

```<code>var dir = './test-new-folder'; // OR var dir = 'test-new-folder';

if (!fs.existsSync(dir)) {
   fs.mkdirSync(dir, '0777', true);
}
</code>```

The above code works properly in my local and creates a folder named 'test-new-folder' inside my root folder.

But after creating it's desktop application on MAC,

Why this code doesn't work? Why doesn't it create 'test-new-folder'? What could be the work around for this?

Also I want to track/get all the data which will be pushed in this newly created folder! Can I get such events? Or any suggestions for this?

答:
As suggested by @lawrence Cherone in the comments, I've followed this: electronjs.org/docs/api/app#appgetpathname

And the solution I've got is below,

```<code>var desktopPath = (electron.app || electron.remote.app).getPath('desktop');

var dir = desktopPath + '/test-new-folder';

if (!fs.existsSync(dir)) {
   fs.mkdirSync(dir, '0777', true);
}
</code>```

Body:
It works properly when I run the same code locally using Electron JS.

var dir = './test-new-folder'; // OR var dir = 'test-new-folder';

if (!fs.existsSync(dir)) {
   fs.mkdirSync(dir, '0777', true);
}

The above code works properly in my local and creates a folder named 'test-new-folder' inside my root folder.

But after creating it's desktop application on MAC,

Why this code doesn't work? Why doesn't it create 'test-new-folder'? What could be the work around for this?

Also I want to track/get all the data which will be pushed in this newly created folder! Can I get such events? Or any suggestions for this?

Body:
As suggested by @lawrence Cherone in the comments, I've followed this: electronjs.org/docs/api/app#appgetpathname

And the solution I've got is below,

var desktopPath = (electron.app || electron.remote.app).getPath('desktop');

var dir = desktopPath + '/test-new-folder';

if (!fs.existsSync(dir)) {
   fs.mkdirSync(dir, '0777', true);
}


问:
Expected 0 arguments but got 1 in ionic 3 provider injectalble issue
When I try to add api connection part in the ionic provider from Angular web app service it shows Expected 0 arguments but got 1 in here:

```<code>@Injectable({
  providedIn: 'root'
})
</code>```

While the same is working in the Angular web project.

Ionic3 provider looks like this:

```<code>import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';

const BASEURL = 'http://domain...';

@Injectable({
  providedIn: 'root'
})
export class AuthProvider {
  constructor(private http: HttpClient) { }

  RegisterUser(body): Observable<any> {
    return this.http.post(`${BASEURL}/register`, body);
  }

  LoginUser(body): Observable<any> {
    return this.http.post(`${BASEURL}/login`, body);
  }
}
</code>```

How to fix this?

答:
change this :

(new in angular 6 wont work in ionic 3)

```<code>@Injectable({
 providedIn: 'root'
})
</code>```

to this

```<code>@Injectable()
</code>```

or
upgrade to ionic 4

Body:
When I try to add api connection part in the ionic provider from Angular web app service it shows Expected 0 arguments but got 1 in here:

@Injectable({
  providedIn: 'root'
})

While the same is working in the Angular web project.

Ionic3 provider looks like this:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';

const BASEURL = 'http://domain...';

@Injectable({
  providedIn: 'root'
})
export class AuthProvider {
  constructor(private http: HttpClient) { }

  RegisterUser(body): Observable<any> {
    return this.http.post(`${BASEURL}/register`, body);
  }

  LoginUser(body): Observable<any> {
    return this.http.post(`${BASEURL}/login`, body);
  }
}

How to fix this?

Body:
change this :

(new in angular 6 wont work in ionic 3)

@Injectable({
 providedIn: 'root'
})

to this

@Injectable()

or
upgrade to ionic 4


问:
ActiveMQ Java consumer throws Transport scheme NOT recognized: [tcp]
I have created the ActiveMQ consumer file in Java. When I am trying to connect to ActiveMQ it shows:

```<code>exception in run method::javax.jms.JMSException: Could not create Transport. Reason: java.io.IOException: Transport scheme NOT recognized: [tcp]
</code>```

When I run the same consumer file as a standalone file its working properly, but with Ant build its not working. I have included activemq-all.jar in build path. But still its not working.

Connection URL: tcp://localhost:61616

import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.MessageListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;

    private void createConnection(String USER, String PASSWORD, String connectionURL) throws Exception{
        this.connectionFactory = new ActiveMQConnectionFactory(USER, PASSWORD, connectionURL);
         // connectionURL = tcp://localhost:61616
        // Create a Connection
        this.connection = connectionFactory.createConnection();
        connection.start();
        connection.setExceptionListener(this);
        // Create a Session
        this.session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    }
```

答:
This issue is due to ANT build.
I have removed the META-INF while creating destination jar
<zipfileset src="activemq-all.jar" excludes="META-INF/**" />

then i have replaced it with the below mentioned command alone:
<zipfileset src="activemq-all.jar">

Body:
I have created the ActiveMQ consumer file in Java. When I am trying to connect to ActiveMQ it shows:

exception in run method::javax.jms.JMSException: Could not create Transport. Reason: java.io.IOException: Transport scheme NOT recognized: [tcp]

When I run the same consumer file as a standalone file its working properly, but with Ant build its not working. I have included activemq-all.jar in build path. But still its not working.

Connection URL: tcp://localhost:61616

import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.ExceptionListener;
import javax.jms.MessageListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnectionFactory;

    private void createConnection(String USER, String PASSWORD, String connectionURL) throws Exception{
        this.connectionFactory = new ActiveMQConnectionFactory(USER, PASSWORD, connectionURL);
         // connectionURL = tcp://localhost:61616
        // Create a Connection
        this.connection = connectionFactory.createConnection();
        connection.start();
        connection.setExceptionListener(this);
        // Create a Session
        this.session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    }


问:
Need 3 digits in column in a CSV-file
I have a script that extracts data from an XML file and put this into an CSV file with 2 columns.
The file looks like this:

```<code>Name, Count
1,34
3,55
15,66
103,99
etc.
</code>```

So far so good...

My problem is that the program that reads the CSV-file always expect 3 digits in the column "Name".

So the CSV-file need to look like this:

```<code>Name, Count
001,34
003,55
015,66
103,99
etc.
</code>```

How can I do this formatting using "Export-CSV"?

Please help I'm stuck here..

答:
Use the -f ( format ) operator with variable

i.e.

```<code>[int] $int = 25;

"{0:D3}" -f $int
</code>```

Here 3 is a number of digits and Output will be :

025

Title: Need 3 digits in column in a CSV-file

Body:
I have a script that extracts data from an XML file and put this into an CSV file with 2 columns.
The file looks like this:

Name, Count
1,34
3,55
15,66
103,99
etc.

So far so good...

My problem is that the program that reads the CSV-file always expect 3 digits in the column "Name".

So the CSV-file need to look like this:

Name, Count
001,34
003,55
015,66
103,99
etc.

How can I do this formatting using "Export-CSV"?

Please help I'm stuck here..

Body:
Use the -f ( format ) operator with variable

i.e.

[int] $int = 25;

"{0:D3}" -f $int

Here 3 is a number of digits and Output will be :

025


问:
What is the proper method to receive consumed costs by virtual machine
I have faced some difficulties with receiving spent money by Azure Virtual Machine.

For example there is metrics for receiving consumption of CPU Usage and CPU Credits Consumed.
https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmname}/providers/microsoft.insights/metrics?api-version=2018-01-01&metricnames=Percentage%20CPU,CPU%20Credits%20Consumed&timespan=2019-05-20T00:00:00Z/2019-05-21T00:00:00Z

So I receive something like this:

```<code> {"cost"=>0.04, "timestamp"=>"2019-05-20T00:26:00Z"}},
 {"cost"=>0.03, "timestamp"=>"2019-05-20T00:27:00Z"}},
 {"cost"=>0.03, "timestamp"=>"2019-05-20T00:28:00Z"}}
</code>```

For whole day it gives me about 57 units (it is important) if I sum all of 1440 results.

However there is also such thing as Usage Details. When I use it:
https://management.azure.com/{scope}/providers/Microsoft.Consumption/usageDetails?api-version=2019-01-01

This request responses with such response:

```<code>"properties"=>
     {"billingPeriodId"=>"/subscriptions/subscription_id/providers/Microsoft.Billing/billingPeriods/201906",
      "usageStart"=>"2019-05-20T00:00:00.0000000Z",
      "usageEnd"=>"2019-05-20T23:59:59.0000000Z",
    "instanceId"=>"/subscriptions/subscription_id/resourceGroups/CLOUD-SHELL-STORAGE-EASTUS/providers/Microsoft.Compute/virtualMachines/name",
      "instanceName"=>"name",
      "instanceLocation"=>"AP East",
      "meterId"=>"some_id",
      "usageQuantity"=>24,
      "pretaxCost"=>24.75,
      "currency"=>"RUB",
      "subscriptionGuid"=>"some guid",
      "subscriptionName"=>"MSDN",
</code>```

So it shows 24.75 RUB for 20th of May.

I would like to know what is the correct way to get proper costs consuming by virtual machine. Thanks in advance

答:
```<code>What resources are charged when deploying a VM?
</code>```

to understand how much does the VM cost , we need to understand what are the resources being used when we use any VM. VMs acquire costs for the VM itself, any premium software running on the VM, the storage account\managed disk associated with the VM, and the networking bandwidth transfers from the VM.

We can get price and metadata information for resource used in an azure subscription using resource rate card API.

Here is the sample rate card api URL.

```<code>https://management.azure.com/subscriptions/{subscription-Id}/providers/Microsoft.Commerce/RateCard?api-version={api-version}&$filter=OfferDurableId eq ’{OfferDurableId}’ and Currency eq ’{Currency}’ and Locale eq ’{Locale}’ and RegionInfo eq ’{RegionInfo}’’
</code>```

Set {OfferDurableId} to a valid Offer ID code (e.g., MS-AZR-0026P). See Microsoft Azure Offer Details for more information on the list of available Offer IDs, country/region availability, and billing currency. The Offer ID parameter consists of the “MS-AZR-“ prefix, plus the Offer ID number.

Set {Currency} to the currency in which the resource rates need to be provided.

Set {Locale} to the culture in which the resource metadata needs to be localized.

Set {RegionInfo} to the 2 letter ISO code where the offer was purchased.

https://management.azure.com/subscriptions/{subscription-Id}/providers/Microsoft.Commerce/RateCard?api-version=2015-06-01-preview&$filter=OfferDurableId eq ’MS-AZR-0003p’ and Currency eq ’USD’ and Locale eq ’en-US’ and RegionInfo eq ’US’

sample response:

```<code>{
   "OfferTerms": [],
   "Meters": [
      {
         "MeterId": "1822fcc4-6059-4cbb-a132-54a187aaac46",
         "MeterName": "Compute Hours",
         "MeterCategory": "Virtual Machines",
         "MeterSubCategory": "Basic_D6 VM (Non-Windows)",
         "Unit": "Hours",
         "MeterTags": [],
         "MeterRates": {
            "0": 3.136
         },
         "EffectiveDate": "2015-02-01T00:00:00Z",
         "IncludedQuantity": 0.0
      },
      {
         "MeterId": "3c5324ad-eb8c-44c6-af9a-6741ae75fc90",
         "MeterName": "Data Transfer Out at 500 Mbps (GB)",
         "MeterCategory": "Networking",
         "MeterSubCategory": "ExpressRoute (IXP)",
         "Unit": "GB",
         "MeterTags": [],
         "MeterRates": {
            "0": 0.1
         },
         "EffectiveDate": "2014-08-01T00:00:00Z",
         "IncludedQuantity": 2048.0
      },

      {
         "MeterId": "9ee077eb-c902-46ef-b7f9-2caeade852e0",
         "MeterName": "Compute Hours",
         "MeterCategory": "Cloud Services",
         "MeterSubCategory": "A6 Cloud Services",
         "Unit": "Hours",
         "MeterTags": [],
         "MeterRates": {
           "0": 0.71
         },
         "EffectiveDate": "2013-12-01T00:00:00Z",
         "IncludedQuantity": 0.0
      },
   …
   ]
   "Currency": "USD",
   "Locale": "en-US",
   "IsTaxIncluded": false,
   "MeterRegion": "US West",
   "Tags": []
}
</code>```

Hope it helps.

Body:
I have faced some difficulties with receiving spent money by Azure Virtual Machine.

For example there is metrics for receiving consumption of CPU Usage and CPU Credits Consumed.
https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Compute/virtualMachines/{vmname}/providers/microsoft.insights/metrics?api-version=2018-01-01&metricnames=Percentage%20CPU,CPU%20Credits%20Consumed&timespan=2019-05-20T00:00:00Z/2019-05-21T00:00:00Z

So I receive something like this:

 {"cost"=>0.04, "timestamp"=>"2019-05-20T00:26:00Z"}},
 {"cost"=>0.03, "timestamp"=>"2019-05-20T00:27:00Z"}},
 {"cost"=>0.03, "timestamp"=>"2019-05-20T00:28:00Z"}}

For whole day it gives me about 57 units (it is important) if I sum all of 1440 results.

However there is also such thing as Usage Details. When I use it:
https://management.azure.com/{scope}/providers/Microsoft.Consumption/usageDetails?api-version=2019-01-01

This request responses with such response:

"properties"=>
     {"billingPeriodId"=>"/subscriptions/subscription_id/providers/Microsoft.Billing/billingPeriods/201906",
      "usageStart"=>"2019-05-20T00:00:00.0000000Z",
      "usageEnd"=>"2019-05-20T23:59:59.0000000Z",
    "instanceId"=>"/subscriptions/subscription_id/resourceGroups/CLOUD-SHELL-STORAGE-EASTUS/providers/Microsoft.Compute/virtualMachines/name",
      "instanceName"=>"name",
      "instanceLocation"=>"AP East",
      "meterId"=>"some_id",
      "usageQuantity"=>24,
      "pretaxCost"=>24.75,
      "currency"=>"RUB",
      "subscriptionGuid"=>"some guid",
      "subscriptionName"=>"MSDN",

So it shows 24.75 RUB for 20th of May.

I would like to know what is the correct way to get proper costs consuming by virtual machine. Thanks in advance

Body:
What resources are charged when deploying a VM?

to understand how much does the VM cost , we need to understand what are the resources being used when we use any VM. VMs acquire costs for the VM itself, any premium software running on the VM, the storage account\managed disk associated with the VM, and the networking bandwidth transfers from the VM.

We can get price and metadata information for resource used in an azure subscription using resource rate card API.

Here is the sample rate card api URL.

https://management.azure.com/subscriptions/{subscription-Id}/providers/Microsoft.Commerce/RateCard?api-version={api-version}&$filter=OfferDurableId eq ’{OfferDurableId}’ and Currency eq ’{Currency}’ and Locale eq ’{Locale}’ and RegionInfo eq ’{RegionInfo}’’

Set {OfferDurableId} to a valid Offer ID code (e.g., MS-AZR-0026P). See Microsoft Azure Offer Details for more information on the list of available Offer IDs, country/region availability, and billing currency. The Offer ID parameter consists of the “MS-AZR-“ prefix, plus the Offer ID number.

Set {Currency} to the currency in which the resource rates need to be provided.

Set {Locale} to the culture in which the resource metadata needs to be localized.

Set {RegionInfo} to the 2 letter ISO code where the offer was purchased.

https://management.azure.com/subscriptions/{subscription-Id}/providers/Microsoft.Commerce/RateCard?api-version=2015-06-01-preview&$filter=OfferDurableId eq ’MS-AZR-0003p’ and Currency eq ’USD’ and Locale eq ’en-US’ and RegionInfo eq ’US’

sample response:

{
   "OfferTerms": [],
   "Meters": [
      {
         "MeterId": "1822fcc4-6059-4cbb-a132-54a187aaac46",
         "MeterName": "Compute Hours",
         "MeterCategory": "Virtual Machines",
         "MeterSubCategory": "Basic_D6 VM (Non-Windows)",
         "Unit": "Hours",
         "MeterTags": [],
         "MeterRates": {
            "0": 3.136
         },
         "EffectiveDate": "2015-02-01T00:00:00Z",
         "IncludedQuantity": 0.0
      },
      {
         "MeterId": "3c5324ad-eb8c-44c6-af9a-6741ae75fc90",
         "MeterName": "Data Transfer Out at 500 Mbps (GB)",
         "MeterCategory": "Networking",
         "MeterSubCategory": "ExpressRoute (IXP)",
         "Unit": "GB",
         "MeterTags": [],
         "MeterRates": {
            "0": 0.1
         },
         "EffectiveDate": "2014-08-01T00:00:00Z",
         "IncludedQuantity": 2048.0
      },

      {
         "MeterId": "9ee077eb-c902-46ef-b7f9-2caeade852e0",
         "MeterName": "Compute Hours",
         "MeterCategory": "Cloud Services",
         "MeterSubCategory": "A6 Cloud Services",
         "Unit": "Hours",
         "MeterTags": [],
         "MeterRates": {
           "0": 0.71
         },
         "EffectiveDate": "2013-12-01T00:00:00Z",
         "IncludedQuantity": 0.0
      },
   …
   ]
   "Currency": "USD",
   "Locale": "en-US",
   "IsTaxIncluded": false,
   "MeterRegion": "US West",
   "Tags": []
}

Hope it helps.


问:
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.

答:
With annotation you can do it only by aproximation by finding a common denominator and poll it. I will show you later. If you want a real dynamic solution you can not use annotations but you can use programmatic configuration. The positive of this solution is that you can change the execution period even in runtime! Here is an example on how to do that:

```<code>  public initializeDynamicScheduledTAsk (ThreadPoolTaskScheduler scheduler,Date start,long executionPeriod) {
    scheduler.schedule(
      new ScheduledTask(),
      new Date(startTime),period
    );
    }
class ScheduledTask implements Runnable{

    @Override
    public void run() {
       // my scheduled logic here
    }
}
</code>```

There is a way to cheat and actually do something with annotations. But you can do that only if precision is not important. What does it mean precision. If you know that you want to start it every 5 seconds but 100ms more or less is not important. If you know that you need to start every 5-6-8 or 10 seconds you can configure one job that is executing every second and check within one if statement how long has it passed since the previous execution. It is very lame, but it works :) as long as you don't need up to millisecond precision. Here is an example:

```<code>public class SemiDynamicScheduledService {

private Long lastExecution;
@Value(#{yourDynamicConfiguration})
private int executeEveryInMS

@Scheduled(fixedDelay=1000)
public semiDynamicScheduledMethod() {
   if (System.currentTimeMS() - lastExecution>executeEveryInMS) {
      lastExecution = System.currentTimeMS();
      // put your processing logic here
   }
}

}
</code>```

I is a bit lame but will do the job for simple cases.

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.

Body:
With annotation you can do it only by aproximation by finding a common denominator and poll it. I will show you later. If you want a real dynamic solution you can not use annotations but you can use programmatic configuration. The positive of this solution is that you can change the execution period even in runtime! Here is an example on how to do that:

  public initializeDynamicScheduledTAsk (ThreadPoolTaskScheduler scheduler,Date start,long executionPeriod) {
    scheduler.schedule(
      new ScheduledTask(),
      new Date(startTime),period
    );
    }
class ScheduledTask implements Runnable{

    @Override
    public void run() {
       // my scheduled logic here
    }
}

There is a way to cheat and actually do something with annotations. But you can do that only if precision is not important. What does it mean precision. If you know that you want to start it every 5 seconds but 100ms more or less is not important. If you know that you need to start every 5-6-8 or 10 seconds you can configure one job that is executing every second and check within one if statement how long has it passed since the previous execution. It is very lame, but it works :) as long as you don't need up to millisecond precision. Here is an example:

public class SemiDynamicScheduledService {

private Long lastExecution;
@Value(#{yourDynamicConfiguration})
private int executeEveryInMS

@Scheduled(fixedDelay=1000)
public semiDynamicScheduledMethod() {
   if (System.currentTimeMS() - lastExecution>executeEveryInMS) {
      lastExecution = System.currentTimeMS();
      // put your processing logic here
   }
}

}

I is a bit lame but will do the job for simple cases.


问:
Python - Average of three values in a while true loop
I'm developing a python script on a raspberry pi with a distance sensor.
My code is working and i can reach the distance but I want to avoid some false positive/negative so I would like to get the average of the last three data.

Here is my code:

while True:
        distance= misura() # GETTING THE REAL DISTANCE IN CM
        print "Distanza : %.2f" % distanza

        avg_distance = <something> # <- HERE I NEED SOMETHING ELEGANT

        if (avg_distance > 30):
            print "NOT PRESENT"
        else:
            print "PRESENT"

        time.sleep(1.5)
```

I would like some function (maybe based on a list?) that returns the average of the last three (or n) distances

IMPORTANT:
I don't want to store ALL the values because this script will run for days and days

答:
If it is your objective to only remember the last three measurements and find their average, consider using a collections.deque object so that when you add to this object, it will only remember the last three elements that were added to it.  You can find the average of the contents in the deque at each iteration:

```<code>from collections import deque
l = deque(maxlen=3) # New
while True:
    distance= misura() # GETTING THE REAL DISTANCE IN CM
    print "Distanza : %.2f" % distanza
    l.append(distance) # New
    #avg_distance = <something> # <- HERE I NEED SOMETHING ELEGANT
    avg_distance = sum(l) / len(l) # Compute average of the last three eleemnts

    if (avg_distance > 30):
        print "NOT PRESENT"
    else:
        print "PRESENT"

    time.sleep(1.5)
</code>```

The nice thing about this is that when the deque is full and you append an item to it, it will remove the oldest added element in the deque and add in the newest element you're trying to add.

Body:
I'm developing a python script on a raspberry pi with a distance sensor.
My code is working and i can reach the distance but I want to avoid some false positive/negative so I would like to get the average of the last three data.

Here is my code:

while True:
        distance= misura() # GETTING THE REAL DISTANCE IN CM
        print "Distanza : %.2f" % distanza

        avg_distance = <something> # <- HERE I NEED SOMETHING ELEGANT

        if (avg_distance > 30):
            print "NOT PRESENT"
        else:
            print "PRESENT"

        time.sleep(1.5)

I would like some function (maybe based on a list?) that returns the average of the last three (or n) distances

IMPORTANT:
I don't want to store ALL the values because this script will run for days and days

Body:
If it is your objective to only remember the last three measurements and find their average, consider using a collections.deque object so that when you add to this object, it will only remember the last three elements that were added to it.  You can find the average of the contents in the deque at each iteration:

from collections import deque
l = deque(maxlen=3) # New
while True:
    distance= misura() # GETTING THE REAL DISTANCE IN CM
    print "Distanza : %.2f" % distanza
    l.append(distance) # New
    #avg_distance = <something> # <- HERE I NEED SOMETHING ELEGANT
    avg_distance = sum(l) / len(l) # Compute average of the last three eleemnts

    if (avg_distance > 30):
        print "NOT PRESENT"
    else:
        print "PRESENT"

    time.sleep(1.5)

The nice thing about this is that when the deque is full and you append an item to it, it will remove the oldest added element in the deque and add in the newest element you're trying to add.


问:
Two way data binding using semantic ui searchable dropdown with vuejs
I am having an issue with Semantic-UI searchable dropdown and Vuejs data binding, at the moment it is only able to model bind 1 changed option regardless of the selected dropdown option. below is my code.

I tried using the @change event but this has brought no results for me.

```<code>           <select
              name="clients"
              id="clients"
              class="ui fluid search selection dropdown uppercase"
              v-model="selected_client"
            >
              <option value>Select Client</option>
              <option
                v-for="(client, index) in clients"
                :key="index"
                :value="client.services"
              >{{client.firstname}}, {{client.lastname}}</option>
            </select>
</code>```

答:
I realized my error, it was not on the @change event handler rather how I was handling the v-bind key as v-bind expect each key to be unique so in my case, I wasn't providing such so I passed the event to a method which filters out the specific client based on the id given as the value. below is the solution which worked for me.

I hope someone will find this useful.

```<code>       <select
          name="clients"
          id="clients"
          class="ui fluid search selection dropdown uppercase"
          @change="clientData($event)"
        >
          <option value>Select Client</option>
          <option
            v-for="client in clients"
            :key="client.id"
            :value="client.id"
          >{{client.firstname}}, {{client.lastname}}</option>
        </select>
</code>```

Body:
I am having an issue with Semantic-UI searchable dropdown and Vuejs data binding, at the moment it is only able to model bind 1 changed option regardless of the selected dropdown option. below is my code.

I tried using the @change event but this has brought no results for me.

           <select
              name="clients"
              id="clients"
              class="ui fluid search selection dropdown uppercase"
              v-model="selected_client"
            >
              <option value>Select Client</option>
              <option
                v-for="(client, index) in clients"
                :key="index"
                :value="client.services"
              >{{client.firstname}}, {{client.lastname}}</option>
            </select>

Body:
I realized my error, it was not on the @change event handler rather how I was handling the v-bind key as v-bind expect each key to be unique so in my case, I wasn't providing such so I passed the event to a method which filters out the specific client based on the id given as the value. below is the solution which worked for me.

I hope someone will find this useful.

       <select
          name="clients"
          id="clients"
          class="ui fluid search selection dropdown uppercase"
          @change="clientData($event)"
        >
          <option value>Select Client</option>
          <option
            v-for="client in clients"
            :key="client.id"
            :value="client.id"
          >{{client.firstname}}, {{client.lastname}}</option>
        </select>


问:
Log::info - Logging user logout in laravel.log
I want add all activities inside my app in the larave.log file.
I was able to add user login inside it but not the logout.

I do that using Laravel 5.8 with a mysql 5 database.

This is code inside HomeController for registering login user loading home view.

```<code>public function index()
{
    Log::info('Utente collegato: '.Auth::user()->name);
    return view( config('configpath.user_home') );// loading user homepage
}
</code>```

The code below is inside Laravel default LoginController

```<code>public function userLogout()
{
    Log::info('User '.Auth::user()->name. 'has logged out');
    Auth::guard('web')->logout();
    return redirect()->route('login');
}
</code>```

With logout I expect to see the message about user logout as in login but I don't see it. Someone can give me an explanation? Thanks!

答:
You have to override the correct method. I think userLogout gets never called from the framework.</p>

```<code>/**
 * Log the user out of the application.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function logout(Request $request)
{
    Log::info('User '.Auth::user()->email.' has logged out');
    Auth::guard('web')->logout();

    return redirect()->route('login');
}
</code>```

Body:
I want add all activities inside my app in the larave.log file.
I was able to add user login inside it but not the logout.

I do that using Laravel 5.8 with a mysql 5 database.

This is code inside HomeController for registering login user loading home view.

public function index()
{
    Log::info('Utente collegato: '.Auth::user()->name);
    return view( config('configpath.user_home') );// loading user homepage
}

The code below is inside Laravel default LoginController

public function userLogout()
{
    Log::info('User '.Auth::user()->name. 'has logged out');
    Auth::guard('web')->logout();
    return redirect()->route('login');
}

With logout I expect to see the message about user logout as in login but I don't see it. Someone can give me an explanation? Thanks!

Body:
You have to override the correct method. I think userLogout gets never called from the framework.

/**
 * Log the user out of the application.
 *
 * @param  \Illuminate\Http\Request  $request
 * @return \Illuminate\Http\Response
 */
public function logout(Request $request)
{
    Log::info('User '.Auth::user()->email.' has logged out');
    Auth::guard('web')->logout();

    return redirect()->route('login');
}


问:
Passing generic DBset entities to DbContext
Here is my dbcontext

```<code>public partial class MyDbContext : DbContext
{
    //dbset 1
    public DbSet<Customer> Customers { get; set; }

    //dbset 2
    public DbSet<Order> Orders { get; set; }
}
</code>```

I want to pass my models i mean Customer and order outside MyDbContext .something like this :

```<code>public partial class MyDbContext<T> : DbContext
{

    public DbSet<T> <T>{ get; set; }

}
</code>```

And a function to get the list of entities to add to my context like this

```<code>addEntityToDbContext(Customer)
addEntityToDbContext(Orders)
</code>```

Is it possible?

I am using EF Core .

答:
I'm not sure what your question is? But DbContext has a generic DbSet method already built in?</p>

```<code>    public virtual DbSet<TEntity> Set<TEntity>() where TEntity : class =>
(DbSet<TEntity>)((IDbSetCache)this).GetOrAddSet(DbContextDependencies.SetSource, typeof(TEntity));
</code>```

Body:
Here is my dbcontext

public partial class MyDbContext : DbContext
{
    //dbset 1
    public DbSet<Customer> Customers { get; set; }

    //dbset 2
    public DbSet<Order> Orders { get; set; }
}

I want to pass my models i mean Customer and order outside MyDbContext .something like this :

public partial class MyDbContext<T> : DbContext
{

    public DbSet<T> <T>{ get; set; }

}

And a function to get the list of entities to add to my context like this

addEntityToDbContext(Customer)
addEntityToDbContext(Orders)

Is it possible?

I am using EF Core .

Body:
I'm not sure what your question is? But DbContext has a generic DbSet method already built in?

    public virtual DbSet<TEntity> Set<TEntity>() where TEntity : class =>
(DbSet<TEntity>)((IDbSetCache)this).GetOrAddSet(DbContextDependencies.SetSource, typeof(TEntity));


问:
Extract string value of an ENUM in a Typescript Object
I have an Enum:

```<code>export enum DistanceMeasure {
Miles, Kilometers
</code>```

}

To use in a user object:

```<code>export class User {
... some stuff
MaxTravelDistance:  number;
DistanceMeasure:    DistanceMeasure;
MaxTravelTime:      TimeSpan;
... some more stuff
</code>```

}

So the info comes from the server as 0 (zero) or 1 for the DistanceMeasure and thats fine.
But I need to present the string e.g. "Miles".

In my (Angular/Ionic) app, the output of

```<code>      console.log(user.DistanceMeasure);
</code>```

is '0' (zero).
However I read that to extract the enum string you should use it as an index.
If I do:

```<code>      console.log(user.DistanceMeasure[0]);
</code>```

It comes back as undefined.

Why is that? since the user.DistanceMeasure is of type DistanceMeasure?
Is it no longer an enum ?
Thanks.

答:
By default, enums have numeric value as 0,1,2...
You can define your enum like:

```<code>export enum DistanceMeasure {
    Miles = 'Miles',
    Kilometers = 'Kilometers'
}
</code>```

And now DistanceMeasure.Miles will have value as 'Miles'.

Body:
I have an Enum:

export enum DistanceMeasure {
Miles, Kilometers

}

To use in a user object:

export class User {
... some stuff
MaxTravelDistance:  number;
DistanceMeasure:    DistanceMeasure;
MaxTravelTime:      TimeSpan;
... some more stuff

}

So the info comes from the server as 0 (zero) or 1 for the DistanceMeasure and thats fine.
But I need to present the string e.g. "Miles".

In my (Angular/Ionic) app, the output of

      console.log(user.DistanceMeasure);

is '0' (zero).
However I read that to extract the enum string you should use it as an index.
If I do:

      console.log(user.DistanceMeasure[0]);

It comes back as undefined.

Why is that? since the user.DistanceMeasure is of type DistanceMeasure?
Is it no longer an enum ?
Thanks.

Body:
By default, enums have numeric value as 0,1,2...
You can define your enum like:

export enum DistanceMeasure {
    Miles = 'Miles',
    Kilometers = 'Kilometers'
}

And now DistanceMeasure.Miles will have value as 'Miles'.


问:
get user specific like by id
im using facebook graph , when im using https://graph.facebook.com/me/likes?........
   im getting all my(User) likes , i want specific like for my fan page..

how can i get specific like by id

example there are 2 likes i want to get  only the 113854025316756(Id):

```<code> {
     "name": "Finzit",
     "category": "Application",
     "id": "113854025316756",
     "created_time": "2011-02-15T16:53:41+0000"
  },
  {
     "name": "\u05d0\u05d9\u05d9\u05e4\u05d5\u05df \u05db\u05d7\u05d5\u05dc \u05dc\u05d1\u05df",
     "category": "Local business",
     "id": "228466071396",
     "created_time": "2010-08-28T18:01:21+0000"
  },
</code>```

thanks

答:
You can use FQL for that, like this </p>

```<code>"SELECT uid, page_id, created_time FROM page_fan
WHERE page_id='PAGE ID'
AND uid='USER ID'";
</code>```

Title: get user specific like by id

Body:
im using facebook graph , when im using https://graph.facebook.com/me/likes?........
   im getting all my(User) likes , i want specific like for my fan page..

how can i get specific like by id

example there are 2 likes i want to get  only the 113854025316756(Id):

 {
     "name": "Finzit",
     "category": "Application",
     "id": "113854025316756",
     "created_time": "2011-02-15T16:53:41+0000"
  },
  {
     "name": "\u05d0\u05d9\u05d9\u05e4\u05d5\u05df \u05db\u05d7\u05d5\u05dc \u05dc\u05d1\u05df",
     "category": "Local business",
     "id": "228466071396",
     "created_time": "2010-08-28T18:01:21+0000"
  },

thanks

Body:
You can use FQL for that, like this

"SELECT uid, page_id, created_time FROM page_fan
WHERE page_id='PAGE ID'
AND uid='USER ID'";