问:
Array receives two of the same values
Sorry if the code is sloppy, I've only been working with QT for the past couple of weeks. I'm working on a small game while studying, and right now I'm working on when the player buys an item from the shop it will be placed it into the character bag.

The Problem is when I buy the item once, it works fine. But if I delete the item after purchase then repurchase the same item again it will put two of the same item into the array even though I purchased one.

I have 3 files used for this.   Inventory.cpp, GameScreen.cpp, Shops.cpp.

GameScreen.cpp is the main file. Here I just initialize everything.

```<code>void GameScreen::initGame(QString &characterName, QString &characterProfession){
    //PASS CHARACTERNAME AND CHARACTERPROFESSION INTO INVENTORY
    inv.initCharacter(characterName, characterProfession);
    //INIT BAG
    inv.initBag();
    //INIT MONEY
    inv.initMoney();
    //SHOPS INITS
    mos.initShop();
    mos.passMoneyToShop(inv.gold, inv.silver, inv.copper);
}
</code>```

This will open the shop window. The Item connect is apart of my problem.

```<code>void GameScreen::on_mapOneShopB_clicked()
{
    mos.setModal(true);

    //SEND THE ITEM INTO BAG
    connect(&mos, SIGNAL(getItemFromMapOneShop(const QString&)), &inv, SLOT(bagAddElement(const QString&)));

    mos.show();
    mos.exec();
}
</code>```

Moving into Shops.cpp. I use polymorphism in this file and that's the reason why you see MapOneShop:: instead of Shops::. Sorry about the confusion. But moving on, I hit the button and it subtracts the item price from my amount of gold.

```<code>void MapOneShop::on_buyB_clicked()
{
    //ONLY WORKS IF I HIT THE ITEM NAME COLUMN THEN HIT BUY
    gold -= itemPrice[ui->treeWidget->currentColumn()];

    //UPDATE INFORMATION
    updateInformationVAndMoneyAfterBuy();

}
</code>```

It then moves into updateInformationVAndMoneyAfterBuy(); which checks that I spent money, and If I did it will emit the item I need. I just emit back to GameScreen.cpp inside of void GameScreen::on_mapOneShopB_clicked() and pass them into Inventory.cpp.

```<code>void MapOneShop::updateInformationVAndMoneyAfterBuy()
{
    //UPDATE INFORMATIONV FIRST TO CHECK MONEY CHANGES

    if(goldCheck != gold)
    {
        emit getUpdatedMoneyFromShop(gold, silver, copper);

        //ITEM NAME IS WHERE I STORE THE NAMES OF THE ITEMS
        emit getItemFromMapOneShop(this->itemName[ui->treeWidget->currentColumn()]);
    }
}
</code>```

Now moving into Inventory.cpp. When the item gets passed into bagAddElement after deleting then repurchasing, I get two of the same items even though only 1 should be passed in. I am using a dynamic array for this. Below I will also show the void Inventory::on_deleteB_clicked, void Inventory::bagDeleteAt and also void Inventory::bagLWPrint functions. The items value is my array holding the shopItem strings.

```<code>void Inventory::bagAddElement(const QString& shopItem)
{
    //I USE THIS TO CHECK THE VALUE shopItem.
    qDebug()<<"bagAddElement: " << shopItem;

    //IF THE CURRENT POSITION IN THE BAG
    //IS BIGGER THAN THE CURRENT SIZE
    //IT WILL INCREASE THE BAG FOR US
    if(nrOfEl >= bagSize)
    {
        bagExpand();
    }

    //CHECK FOR VALUES INSIDE ARRAY AND CHECK IF THEY ARE NULL
    //IF SO, IT WILL ADD THE ITEM INTO THE NULL POSITION
    for(int i = 0; i < bagSize; i++)
    {
        if(items[i] == nullptr)
        {
            nrOfEl = i;
            items[nrOfEl++] = shopItem;
            break;
        }
    }

    //UPDATE WIDGET LIST
    bagLWPrint();
}
</code>```

Here I pass the currently selected row value inside bagLW and pass it into void Inventory::bagDeleteAt.

```<code>void Inventory::on_deleteB_clicked()
{
    //BagLW IS A LIST WIDGET
    bagDeleteAt(bagLW->currentRow());
}
</code>```

Now we look for the what's inside items[row] and set it to nullptr. Then we go into void Inventory::bagLWPrint.

```<code>void Inventory::bagDeleteAt(int row)
{
    if(items[row] == nullptr)
    {
        //IF THE ITEM IS ALREADY NULL WILL PRINT A MESSAGE
        QMessageBox::information(this,"Bag","No item in that slot");
    }
    else
    {
        //SET CURRENTLY SELECTED ITEM TO NULL
        items[row] = nullptr;
        bagLWPrint();
    }
}
</code>```

I clear bagLW and refill it with the updated array.

```<code>void Inventory::bagLWPrint()
{
    bagLW->clear();
    for(int i = 0; i < bagSize; i++)
    {
        if(items[i] != nullptr)
        {
            bagLW->addItem(items[i]);
        }
        if(items[i] == nullptr)
        {
            bagLW->addItem(items[i]);
        }
    }
}
</code>```

Other notes.

-The item only gets doubled when inserted into void Inventory::bagAddElement.

-I tried adding another item inside of void GameScreen::initGame and it did not double after deleting and re-entering.

Sorry for such a long question. And any help would be much, much appreciated.

```<code>void Inventory::bagExpand()
{
    //1: INCREASE BAGSPACE
    bagSize *= 2;
    //2: CREATE TEMP ARRAY
    QString *tempItems = new QString[bagSize];
    //3: COPY OVER VALID VALUES FROM OLD ARRAY
    for(int i = 0; i < nrOfEl; i++)
    {
       tempItems[i] = items[i];
    }
    //4: DELETE OLD ARRAY MEMORY
    delete[] items;
    //5: POINT OLD ARRAY POINTER TO NEW ARRAY LOCATION
    items = tempItems;
    //PRINT BAGLW - (UDPATE)
    bagLWPrint();
    qDebug()<<"Bag has increased";
}
</code>```

答:
The problem is that you connect and re-connect the getItemFromMapOneShop signal on every button click. That means that on first click, you add it once (signal triggered, 1 slot connected). On the second click, you add it twice (signal triggered, 2 slots connected). And so on.

QObjects manage a list of all connected slots per signal, and call each of them. Connecting a slot multiple times will call it that many times

You should connect the singal only once, e.g. in the constructor; or disconnect the signal when no longer used

As @Andéon Evain pointed out, you could also use Qt::UniqueConnection. This will not add a duplicate connection if it already exists (considering sender, signal, receiver, slot). That might be useful for cases where it's unknown if already connected; not in your simple case

Title: Array receives two of the same values

Body:
Sorry if the code is sloppy, I've only been working with QT for the past couple of weeks. I'm working on a small game while studying, and right now I'm working on when the player buys an item from the shop it will be placed it into the character bag.

The Problem is when I buy the item once, it works fine. But if I delete the item after purchase then repurchase the same item again it will put two of the same item into the array even though I purchased one.

I have 3 files used for this.   Inventory.cpp, GameScreen.cpp, Shops.cpp.

GameScreen.cpp is the main file. Here I just initialize everything.

void GameScreen::initGame(QString &characterName, QString &characterProfession){
    //PASS CHARACTERNAME AND CHARACTERPROFESSION INTO INVENTORY
    inv.initCharacter(characterName, characterProfession);
    //INIT BAG
    inv.initBag();
    //INIT MONEY
    inv.initMoney();
    //SHOPS INITS
    mos.initShop();
    mos.passMoneyToShop(inv.gold, inv.silver, inv.copper);
}

This will open the shop window. The Item connect is apart of my problem.

void GameScreen::on_mapOneShopB_clicked()
{
    mos.setModal(true);

    //SEND THE ITEM INTO BAG
    connect(&mos, SIGNAL(getItemFromMapOneShop(const QString&)), &inv, SLOT(bagAddElement(const QString&)));

    mos.show();
    mos.exec();
}

Moving into Shops.cpp. I use polymorphism in this file and that's the reason why you see MapOneShop:: instead of Shops::. Sorry about the confusion. But moving on, I hit the button and it subtracts the item price from my amount of gold.

void MapOneShop::on_buyB_clicked()
{
    //ONLY WORKS IF I HIT THE ITEM NAME COLUMN THEN HIT BUY
    gold -= itemPrice[ui->treeWidget->currentColumn()];

    //UPDATE INFORMATION
    updateInformationVAndMoneyAfterBuy();

}

It then moves into updateInformationVAndMoneyAfterBuy(); which checks that I spent money, and If I did it will emit the item I need. I just emit back to GameScreen.cpp inside of void GameScreen::on_mapOneShopB_clicked() and pass them into Inventory.cpp.

void MapOneShop::updateInformationVAndMoneyAfterBuy()
{
    //UPDATE INFORMATIONV FIRST TO CHECK MONEY CHANGES

    if(goldCheck != gold)
    {
        emit getUpdatedMoneyFromShop(gold, silver, copper);

        //ITEM NAME IS WHERE I STORE THE NAMES OF THE ITEMS
        emit getItemFromMapOneShop(this->itemName[ui->treeWidget->currentColumn()]);
    }
}

Now moving into Inventory.cpp. When the item gets passed into bagAddElement after deleting then repurchasing, I get two of the same items even though only 1 should be passed in. I am using a dynamic array for this. Below I will also show the void Inventory::on_deleteB_clicked, void Inventory::bagDeleteAt and also void Inventory::bagLWPrint functions. The items value is my array holding the shopItem strings.

void Inventory::bagAddElement(const QString& shopItem)
{
    //I USE THIS TO CHECK THE VALUE shopItem.
    qDebug()<<"bagAddElement: " << shopItem;

    //IF THE CURRENT POSITION IN THE BAG
    //IS BIGGER THAN THE CURRENT SIZE
    //IT WILL INCREASE THE BAG FOR US
    if(nrOfEl >= bagSize)
    {
        bagExpand();
    }

    //CHECK FOR VALUES INSIDE ARRAY AND CHECK IF THEY ARE NULL
    //IF SO, IT WILL ADD THE ITEM INTO THE NULL POSITION
    for(int i = 0; i < bagSize; i++)
    {
        if(items[i] == nullptr)
        {
            nrOfEl = i;
            items[nrOfEl++] = shopItem;
            break;
        }
    }

    //UPDATE WIDGET LIST
    bagLWPrint();
}

Here I pass the currently selected row value inside bagLW and pass it into void Inventory::bagDeleteAt.

void Inventory::on_deleteB_clicked()
{
    //BagLW IS A LIST WIDGET
    bagDeleteAt(bagLW->currentRow());
}

Now we look for the what's inside items[row] and set it to nullptr. Then we go into void Inventory::bagLWPrint.

void Inventory::bagDeleteAt(int row)
{
    if(items[row] == nullptr)
    {
        //IF THE ITEM IS ALREADY NULL WILL PRINT A MESSAGE
        QMessageBox::information(this,"Bag","No item in that slot");
    }
    else
    {
        //SET CURRENTLY SELECTED ITEM TO NULL
        items[row] = nullptr;
        bagLWPrint();
    }
}

I clear bagLW and refill it with the updated array.

void Inventory::bagLWPrint()
{
    bagLW->clear();
    for(int i = 0; i < bagSize; i++)
    {
        if(items[i] != nullptr)
        {
            bagLW->addItem(items[i]);
        }
        if(items[i] == nullptr)
        {
            bagLW->addItem(items[i]);
        }
    }
}

Other notes.

-The item only gets doubled when inserted into void Inventory::bagAddElement.

-I tried adding another item inside of void GameScreen::initGame and it did not double after deleting and re-entering.

Sorry for such a long question. And any help would be much, much appreciated.

void Inventory::bagExpand()
{
    //1: INCREASE BAGSPACE
    bagSize *= 2;
    //2: CREATE TEMP ARRAY
    QString *tempItems = new QString[bagSize];
    //3: COPY OVER VALID VALUES FROM OLD ARRAY
    for(int i = 0; i < nrOfEl; i++)
    {
       tempItems[i] = items[i];
    }
    //4: DELETE OLD ARRAY MEMORY
    delete[] items;
    //5: POINT OLD ARRAY POINTER TO NEW ARRAY LOCATION
    items = tempItems;
    //PRINT BAGLW - (UDPATE)
    bagLWPrint();
    qDebug()<<"Bag has increased";
}


来源: stackexchange

问:
How can i understand whether the column type is numerical or numerical categorical?
The dataframe that i am using has columns categorical and numerical. For example ;

```<code>a       b
1       1
1.35    2
2.42    3
3       3
</code>```

let's think b is numerical categorical column. But sometimes some indexes may be removed. So in this case i need to fill the indexes that have removed. If i know the column is categorical so i will fill the empty column with the previous column's value. So how can i understand the column is categorical or not?
Thanks in advance.

答:
Came across this now and I think it should be the first approach:

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.api.types.infer_dtype.html

You could check all the unique values that a column holds and decide

```<code>#List unique values in the df['name'] column
df.name.unique()
</code>```

Pandas does support categorical data type dtype="category"

So you could change the type of the column to category for using this knowledge in further calculations

ContentLicense: CC BY-SA 4.0

Body:
The dataframe that i am using has columns categorical and numerical. For example ;

a       b
1       1
1.35    2
2.42    3
3       3

let's think b is numerical categorical column. But sometimes some indexes may be removed. So in this case i need to fill the indexes that have removed. If i know the column is categorical so i will fill the empty column with the previous column's value. So how can i understand the column is categorical or not?
Thanks in advance.

Body:
Came across this now and I think it should be the first approach:

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.api.types.infer_dtype.html

You could check all the unique values that a column holds and decide

#List unique values in the df['name'] column
df.name.unique()

Pandas does support categorical data type dtype="category"

So you could change the type of the column to category for using this knowledge in further calculations


问:
Change view when using webBrowser to browse directories
imagine you are using webBrowser control to browse local file system, so it behaves like Explorer

WebBrowser wb = new WebBrowser();

wb.Navigate(@"c:\");

Now it displays contents of c:\ directory. But I'd like it to programatically set the view mode to "Details" view and not to display whatever mode the logged-in user currently uses.

Thanks

答:
You might want to take a look at the documentation for the IShellBrowser interface:

http://msdn.microsoft.com/en-us/library/bb775123(VS.85).aspx

You are probably going to have to find the IServiceProvider interface implementation on the web browser to get to this interface, and all of it is more than likely going to have to be done through COM interop.

OwnerDisplayName: Axarydax

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: casperOne


问:
SQL - sum data for all time, 30 days and 90 days for multiple columns indiviually
BACKGROUND:

I have data that looks like this

```<code>date        src    subsrc   subsubsrc   param1  param2
2020-02-01  src1    ksjd    dfd8        47      31
2020-02-02  src1    djsk    zmnc        44      95
2020-02-03  src2    skdj    awes        92      100
2020-02-04  src2    mxsf    kajs        80      2
2020-02-05  src3    skdj    asio        46      53
2020-02-06  src3    dekl    jdqo        19      18
2020-02-07  src3    dskl    dqqq        69      18
2020-02-08  src4    sqip    riow        64      46
2020-02-09  src5    ss01    qwep        34      34
</code>```

I am trying to aggregate for all time, last 30 days and last 90 days (no rolling sum)

So my final data would look like this:

```<code>src     subsrc  subsubsrc   p1_all  p1_30   p1_90   p2_all  p2_30   p2_90
src1    ksjd    dfd8        7       1       7       98      7        98
src1    djsk    zmnc        0       0       0       0       0         0
src2    skdj    awes        12      12      12      4       4         4
src2    mxsf    kajs        6       6       6       31      31       31
src3    skdj    asio        0       0       0       0       0         0
src3    dekl    jdqo        20      20      20      17      17        17
src3    dskl    dqqq        3       3       3       4       4         4
src4    sqip    qwep        0       0       0       0       0         0
src5    ss01    qwes        15      15      15      2       2         2
</code>```

ABOUT DATA:

This is only dummy data and therefore incorrect.

There are tens of thousands of rows in my data.

There are a dozen of src columns that make up the key for the table.

There are a dozen of param columns that I have to sum for 30 and 90 and all time.

Also there are null values in param columns.

Also there are might be multiple rows for same day and src column.

New data is being added every day and the query is probably going to be run every day to get the latest 30, 90, all time data.

WHAT I HAVE TRIED:

This is what I have come up with:

```<code>SELECT src, subsubsrc, subsubsrc,
SUM(param1) as param1_all,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 30 THEN param1 END) as param1_30,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 90 THEN param1 END) as param1_90,
SUM(param2) as param2_all,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 30 THEN param2 END) as param2_30,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 90 THEN param2 END) as param2_90,
FROM `MY_TABLE`
GROUP BY src
ORDER BY src
</code>```

This actually works but I can anticipate how long this query is going to become for multiple sources and even more param columns.

I have been trying something called "Filtered aggregate functions (or manual pivot)" explained HERE. But I am unable to understand/implement it for my case.

Also  I have looked at dozens of answers and most of them are running sums for each day OR are complicated cases of this basic calculation. Maybe I am not searching it correctly.

As you can see I am newbie in SQL and would really appreciate any help.

答:
Your code looks good. Your RDBMS needs to loop all records under the hood and do some calculations. One thing that you can improve is that you are calculating date differences for all records. It would make sense to calculate the moment 30 days ago and 90 days ago beforehand, respectively and only compare the dates against those.

Since you already know that the number of rows and parameters will increase in the future, it makes sense to create a cron job which daily computes this in the following manner:

the first time it calculates the values, it should store all the results along with the date it was running at (maybe into a table dedicated for this analytics)

on subsequent days you can calculate the all time sum by loading the items which were created since the last check

you will still need to calculate the 30 and 90 day stuff, but that would be much less of a problem than calculating this for all time

If you do this properly and have daily information, then later on you will be able to analyze trends in history as well.

Body:
BACKGROUND:

I have data that looks like this

date        src    subsrc   subsubsrc   param1  param2
2020-02-01  src1    ksjd    dfd8        47      31
2020-02-02  src1    djsk    zmnc        44      95
2020-02-03  src2    skdj    awes        92      100
2020-02-04  src2    mxsf    kajs        80      2
2020-02-05  src3    skdj    asio        46      53
2020-02-06  src3    dekl    jdqo        19      18
2020-02-07  src3    dskl    dqqq        69      18
2020-02-08  src4    sqip    riow        64      46
2020-02-09  src5    ss01    qwep        34      34

I am trying to aggregate for all time, last 30 days and last 90 days (no rolling sum)

So my final data would look like this:

src     subsrc  subsubsrc   p1_all  p1_30   p1_90   p2_all  p2_30   p2_90
src1    ksjd    dfd8        7       1       7       98      7        98
src1    djsk    zmnc        0       0       0       0       0         0
src2    skdj    awes        12      12      12      4       4         4
src2    mxsf    kajs        6       6       6       31      31       31
src3    skdj    asio        0       0       0       0       0         0
src3    dekl    jdqo        20      20      20      17      17        17
src3    dskl    dqqq        3       3       3       4       4         4
src4    sqip    qwep        0       0       0       0       0         0
src5    ss01    qwes        15      15      15      2       2         2

ABOUT DATA:

This is only dummy data and therefore incorrect.

There are tens of thousands of rows in my data.

There are a dozen of src columns that make up the key for the table.

There are a dozen of param columns that I have to sum for 30 and 90 and all time.

Also there are null values in param columns.

Also there are might be multiple rows for same day and src column.

New data is being added every day and the query is probably going to be run every day to get the latest 30, 90, all time data.

WHAT I HAVE TRIED:

This is what I have come up with:

SELECT src, subsubsrc, subsubsrc,
SUM(param1) as param1_all,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 30 THEN param1 END) as param1_30,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 90 THEN param1 END) as param1_90,
SUM(param2) as param2_all,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 30 THEN param2 END) as param2_30,
SUM(CASE WHEN DATE_DIFF(CURRENT_DATE,date,day) <= 90 THEN param2 END) as param2_90,
FROM `MY_TABLE`
GROUP BY src
ORDER BY src

This actually works but I can anticipate how long this query is going to become for multiple sources and even more param columns.

I have been trying something called "Filtered aggregate functions (or manual pivot)" explained HERE. But I am unable to understand/implement it for my case.

Also  I have looked at dozens of answers and most of them are running sums for each day OR are complicated cases of this basic calculation. Maybe I am not searching it correctly.

As you can see I am newbie in SQL and would really appreciate any help.


问:
Java 8 Jackson Immutable Class Deserialization
I am trying to deserialize a JSON string to a java pojo class that only has an all parameters constructor and getters. All the fields are final and the class is immutable. Here is my java pojo object:

Foo.java

```<code>public class Foo {
    private final int id;
    private final int cId;
    private final String cName;
    private final String code;
    private final String display;

    public Foo(final int id,
               final int cId,
               final String cName,
               final String code,
               final String display) {
        this.id = id;
        this.cId = cId;
        this.cName = cName;
        this.code = code;
        this.display = display;
    }

    //Some copy constructor
    public Foo(final FooB fooB) {
        this.id = fooB.getId();
        this.cId = fooB.getCId();
        this.cName = fooB.getContractorCName();
        this.code = fooB.getCode();
        this.display = fooB.getDisplay();
    }

    public int getId() {
        return id;
    }

    public int getCId() {
        return cId;
    }

    public String getCName() {
        return cName;
    }

    public String getCode() {
        return code;
    }

    public String getDisplay() {
        return display;
    }
}
</code>```

And here's my test:

```<code>public static void main(String[] args) {
    ParameterNamesModule pnm = new ParameterNamesModule(JsonCreator.Mode.PROPERTIES);
    ObjectMapper mapper = new ObjectMapper().enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES).registerModule(pnm);
    String json = "{\"id\":19,\"cId\":13234,\"cName\":\"SOME NAME\",\"code\":\"8EJ4\",\"display\":\"SOME DISPLAY NAME\"}";
    try {
        mapper.readValue(json, Foo.class);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
</code>```

However when I run this I get the following error:

```<code>objc[58537]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/bin/java (0x109dbf4c0) and /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/libinstrument.dylib (0x109e874e0). One of the two will be used. Which one is undefined.
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.test.Foo` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (String)"{"id":19,"cId":13234,"cName":"SOME NAME","code":"8EJ4","display":"SOME DISPLAY NAME"}"; line: 1, column: 2]
    at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67)
    at com.fasterxml.jackson.databind.DeserializationContext.reportBadDefinition(DeserializationContext.java:1451)
    at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1027)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1290)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:326)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:159)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4001)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2992)
    at JacksonCreator.main(JacksonCreator.java:18)
</code>```

What am I doing wrong? I am using version 2.9.4 of the Jackson

答:
try this

@JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
public Foo(@JsonProperty ("id") final int id,
           @JsonProperty ("cId")   final int cId,
              ...) {
        this.id = id;
        this.cId = cId;
       ...
    }

ContentLicense: CC BY-SA 3.0

Body:
I am trying to deserialize a JSON string to a java pojo class that only has an all parameters constructor and getters. All the fields are final and the class is immutable. Here is my java pojo object:

Foo.java

public class Foo {
    private final int id;
    private final int cId;
    private final String cName;
    private final String code;
    private final String display;

    public Foo(final int id,
               final int cId,
               final String cName,
               final String code,
               final String display) {
        this.id = id;
        this.cId = cId;
        this.cName = cName;
        this.code = code;
        this.display = display;
    }

    //Some copy constructor
    public Foo(final FooB fooB) {
        this.id = fooB.getId();
        this.cId = fooB.getCId();
        this.cName = fooB.getContractorCName();
        this.code = fooB.getCode();
        this.display = fooB.getDisplay();
    }

    public int getId() {
        return id;
    }

    public int getCId() {
        return cId;
    }

    public String getCName() {
        return cName;
    }

    public String getCode() {
        return code;
    }

    public String getDisplay() {
        return display;
    }
}

And here's my test:

public static void main(String[] args) {
    ParameterNamesModule pnm = new ParameterNamesModule(JsonCreator.Mode.PROPERTIES);
    ObjectMapper mapper = new ObjectMapper().enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES).registerModule(pnm);
    String json = "{\"id\":19,\"cId\":13234,\"cName\":\"SOME NAME\",\"code\":\"8EJ4\",\"display\":\"SOME DISPLAY NAME\"}";
    try {
        mapper.readValue(json, Foo.class);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

However when I run this I get the following error:

objc[58537]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/bin/java (0x109dbf4c0) and /Library/Java/JavaVirtualMachines/jdk1.8.0_121.jdk/Contents/Home/jre/lib/libinstrument.dylib (0x109e874e0). One of the two will be used. Which one is undefined.
com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.test.Foo` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
 at [Source: (String)"{"id":19,"cId":13234,"cName":"SOME NAME","code":"8EJ4","display":"SOME DISPLAY NAME"}"; line: 1, column: 2]
    at com.fasterxml.jackson.databind.exc.InvalidDefinitionException.from(InvalidDefinitionException.java:67)
    at com.fasterxml.jackson.databind.DeserializationContext.reportBadDefinition(DeserializationContext.java:1451)
    at com.fasterxml.jackson.databind.DeserializationContext.handleMissingInstantiator(DeserializationContext.java:1027)
    at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.deserializeFromObjectUsingNonDefault(BeanDeserializerBase.java:1290)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:326)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:159)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4001)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2992)
    at JacksonCreator.main(JacksonCreator.java:18)

What am I doing wrong? I am using version 2.9.4 of the Jackson


问:
zend framework url generation problems
I'm having some difficulties generating simple urls with zf version 1.11.6. I'm using the url helper for this.

Example:

$this->url(array('controller' => 'index', 'action' => 'index'))

$this->url(array('controller' => 'index', 'action' => 'view', 'id' => 1))

Result:

domain.com/index/index/id/1

domain.com/index/view/id/1

As you can see, the problem is that even I have not specified any id param to the first rule, the generated url contains it. This happens also with action. If I let the first rule without the action parameter, it will be generated having the view value (instead of using the default value of index). Let's say that I can live with the action thing, but this is absurd when it comes to the other parameters.

This happens even though I use the first rule inside my controller and the second one inside a view file.

Any thoughts on this ? Thank you.

答:
```<code>try this
$this->url(array('controller'=>'index','action'=>'index'), 'default', true)
</code>```

Title: zend framework url generation problems


问:
Why can't i filter a Deep nested query in graphql?
So i just started using graphql recently (last week to be precise). I get the concept of being able to filter queries with the 'where' argument and all but i noticed when i try to get objects from a deep nested query it becomes somewhat impossible. So say i have 'domestic_worker_nextofkin' query that should get fullname, mobile_phone1, and relationship where 'archived' _is_null equals true as given below:

```<code>domestic_workers_nextofkin(where: {archived:{_is_null: true}}){
    full_name
    mobile_phone1
    domestic_workers_relationships{
      relationship
    }
  }
}
</code>```

The query above does it's intended job and gets the full_name, mobile_phone1 and relationship.

But my current problem is that when this query is deeply nested as shown below (the asterisked code):

```<code>query User($userId: Int) {
     domestic_workers_news{
          title
          date_created
          summary
          url
        }
    users_user(where: {id: {_eq: $userId}}) {
      domestic_workers_pictures(order_by: {id: desc}, limit: 1) {
        id
      }
      id
      password
      username
      first_name
      last_name
      email
      gender
      birth_date
      mobile_phone1
      mobile_phone2
      home_address_street
      home_address_town
      home_address_lga
      home_address_state
      home_address_country
      home_address_postal_code
      job_title
      workplace
      verified
      agreed_terms
      date_joined
      last_modified
      domestic_workers_workers {
        domestic_workers_pictures(order_by: {id: desc}, limit: 1) {
          id
        }
        id
        first_name
        last_name
        other_name
        email
        mobile_phone1
        mobile_phone2
        home_town
        home_state
        service
        birth_date
        gender
        date_created
        current_employer_id
        domestic_workers_relationships{
          id
          payment
          payment_currency
          start_date
          relationship
          domestic_workers_agent {
            full_name
            mobile_phone1
            domestic_workers_relationships{
              relationship
            }
            domestic_workers_pictures(order_by: {id: desc}, limit: 1) {
              id
            }
          }

**domestic_workers_nextofkin (where: {archived:{_is_null: true}}) {
        full_name
        mobile_phone1
         domestic_workers_relationships{
          relationship
        }
      }
    }**
        domestic_workers_reviews {
          id
          score
          summary
          date_created
          users_user {
            first_name
            last_name
            domestic_workers_pictures(order_by: {id: desc}, limit: 1) {
              id
            }
          }
        }
        employerRelationships: domestic_workers_relationships(order_by: {id: desc}, limit: 1, where: {relationship: {_eq: "Employer"}}) {
         end_date
         relationship
        }
      }
    }
   }
</code>```

It shows the 'where' argument highlighted as red, which possibly means that the 'where' argument shouldnt be placed there which seems rather confusing to me. Can anyone explain why this happens and show me a workaround to pull off the task i'm trying to perform? Thanks.

答:
From the docs:

The where argument can be used in array relationships as well to filter the nested objects. Object relationships have only one nested object and hence they do not expose the where argument.

users_user is an object relationship (it returns a single object instead of an array of them), so it cannot be filtered.

Body:
So i just started using graphql recently (last week to be precise). I get the concept of being able to filter queries with the 'where' argument and all but i noticed when i try to get objects from a deep nested query it becomes somewhat impossible. So say i have 'domestic_worker_nextofkin' query that should get fullname, mobile_phone1, and relationship where 'archived' _is_null equals true as given below:

domestic_workers_nextofkin(where: {archived:{_is_null: true}}){
    full_name
    mobile_phone1
    domestic_workers_relationships{
      relationship
    }
  }
}

The query above does it's intended job and gets the full_name, mobile_phone1 and relationship.

But my current problem is that when this query is deeply nested as shown below (the asterisked code):

query User($userId: Int) {
     domestic_workers_news{
          title
          date_created
          summary
          url
        }
    users_user(where: {id: {_eq: $userId}}) {
      domestic_workers_pictures(order_by: {id: desc}, limit: 1) {
        id
      }
      id
      password
      username
      first_name
      last_name
      email
      gender
      birth_date
      mobile_phone1
      mobile_phone2
      home_address_street
      home_address_town
      home_address_lga
      home_address_state
      home_address_country
      home_address_postal_code
      job_title
      workplace
      verified
      agreed_terms
      date_joined
      last_modified
      domestic_workers_workers {
        domestic_workers_pictures(order_by: {id: desc}, limit: 1) {
          id
        }
        id
        first_name
        last_name
        other_name
        email
        mobile_phone1
        mobile_phone2
        home_town
        home_state
        service
        birth_date
        gender
        date_created
        current_employer_id
        domestic_workers_relationships{
          id
          payment
          payment_currency
          start_date
          relationship
          domestic_workers_agent {
            full_name
            mobile_phone1
            domestic_workers_relationships{
              relationship
            }
            domestic_workers_pictures(order_by: {id: desc}, limit: 1) {
              id
            }
          }

**domestic_workers_nextofkin (where: {archived:{_is_null: true}}) {
        full_name
        mobile_phone1
         domestic_workers_relationships{
          relationship
        }
      }
    }**
        domestic_workers_reviews {
          id
          score
          summary
          date_created
          users_user {
            first_name
            last_name
            domestic_workers_pictures(order_by: {id: desc}, limit: 1) {
              id
            }
          }
        }
        employerRelationships: domestic_workers_relationships(order_by: {id: desc}, limit: 1, where: {relationship: {_eq: "Employer"}}) {
         end_date
         relationship
        }
      }
    }
   }

It shows the 'where' argument highlighted as red, which possibly means that the 'where' argument shouldnt be placed there which seems rather confusing to me. Can anyone explain why this happens and show me a workaround to pull off the task i'm trying to perform? Thanks.


问:
Use PagedListAdapter inside NestedScrollView
I have a RecyclerView that has a PagedListAdapter.

When I put the RecyclerView inside NestedScrollView the PagedList cannot compute the end of the list so start requests continuous burst for new data.

The main question is How should I use PagedListAdapter inside NestedScrollView?

答:
I had a similar problem, and it seems to be caused by the fact that NestedScrollView provides infinite dimensions and so RecyclerView will layout all its children. so I looked on github and found an implementation of NestedScrollView that solved the problem by passing View.MeasureSpec.AT_MOST down to the RecyclerView:

https://gist.github.com/danaimset/abacaa50d746a4537686a08ecc33c1a9


问:
Jmeter - JSON Extractor - issue with extracting the exact decimal value
I'm writing a test to assert that all amount values in a json contain 2 digits after the decimal point.
The JSON Extractor appears to ignore zero when reading the decimal values from the Json. So for example 8.50 will be 8.5 and consequently exact assertions are failing.

Sample Json that I added to the Dummy Sampler

```<code>{
    "shop": {
        "book": [
            {
                "author": "Author 1",
                "title": "Title 1",
                "price": 8.50
            },
        ],
        }
    },
}
</code>```

My response assertion for price is set to 8.50

Assertion result

In the results I get a failure as it indicates 8.5 was extracted rather than 8.50

Is there any steps needed to force the extractor to read the value exactly as it appears in the json?

答:
JMeter's JSON Assertion relies on JayWay JsonPath and this underlying library has a bug inside.

You might want to report this issue at their GitHub and if/once it will be resolved - create an enhancement request for JMeter to use this newer better library.

In the meantime you can use JSR223 Assertion as the workaround, the relevant Groovy code would be:

```<code>def expectedPrice = 8.50

def actualPrice = new groovy.json.JsonSlurper().parse(prev.getResponseData()).shop.book[0].price

if (expectedPrice != actualPrice) {
    AssertionResult.setFailure(true)
    AssertionResult.setFailureMessage('Price mismatch, expected: ' +  expectedPrice + ', got: ' + actualPrice)
}
</code>```

More information:

Apache Groovy: Parsing and producing JSON

Scripting JMeter Assertions in Groovy - A Tutorial

Body:
I'm writing a test to assert that all amount values in a json contain 2 digits after the decimal point.
The JSON Extractor appears to ignore zero when reading the decimal values from the Json. So for example 8.50 will be 8.5 and consequently exact assertions are failing.

Sample Json that I added to the Dummy Sampler

{
    "shop": {
        "book": [
            {
                "author": "Author 1",
                "title": "Title 1",
                "price": 8.50
            },
        ],
        }
    },
}

My response assertion for price is set to 8.50

Assertion result

In the results I get a failure as it indicates 8.5 was extracted rather than 8.50

Is there any steps needed to force the extractor to read the value exactly as it appears in the json?

Body:
JMeter's JSON Assertion relies on JayWay JsonPath and this underlying library has a bug inside.

You might want to report this issue at their GitHub and if/once it will be resolved - create an enhancement request for JMeter to use this newer better library.

In the meantime you can use JSR223 Assertion as the workaround, the relevant Groovy code would be:

def expectedPrice = 8.50

def actualPrice = new groovy.json.JsonSlurper().parse(prev.getResponseData()).shop.book[0].price

if (expectedPrice != actualPrice) {
    AssertionResult.setFailure(true)
    AssertionResult.setFailureMessage('Price mismatch, expected: ' +  expectedPrice + ', got: ' + actualPrice)
}

More information:

Apache Groovy: Parsing and producing JSON

Scripting JMeter Assertions in Groovy - A Tutorial


问:
How to fix ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1056)?
I am trying to send an email with python, but it keeps saying ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1056). Here is my code:

server = smtplib.SMTP_SSL('smtp.mail.com', 587)
server.login("something0@mail.com", "password")
server.sendmail(
"something0@mail.com",
"something@mail.com",
"email text")
server.quit()
```

Do you know what is wrong?

答:
The port for SSL is 465 and not 587, however when I used SSL the mail arrived to the junk mail.

For me the thing that worked was to use TLS over regular SMTP instead of SMTP_SSL.

Note that this is a secure method as TLS is also a cryptographic protocol (like SSL).

```<code>import smtplib, ssl

port = 587  # For starttls
smtp_server = "smtp.gmail.com"
sender_email = "my@gmail.com"
receiver_email = "your@gmail.com"
password = input("Type your password and press enter:")
message = """\
Subject: Hi there

This message is sent from Python."""

context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
    server.ehlo()  # Can be omitted
    server.starttls(context=context)
    server.ehlo()  # Can be omitted
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message)
</code>```

provided thanks to the real python tutorial.

Body:
I am trying to send an email with python, but it keeps saying ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1056). Here is my code:

server = smtplib.SMTP_SSL('smtp.mail.com', 587)
server.login("something0@mail.com", "password")
server.sendmail(
"something0@mail.com",
"something@mail.com",
"email text")
server.quit()

Do you know what is wrong?

Body:
The port for SSL is 465 and not 587, however when I used SSL the mail arrived to the junk mail.

For me the thing that worked was to use TLS over regular SMTP instead of SMTP_SSL.

Note that this is a secure method as TLS is also a cryptographic protocol (like SSL).

import smtplib, ssl

port = 587  # For starttls
smtp_server = "smtp.gmail.com"
sender_email = "my@gmail.com"
receiver_email = "your@gmail.com"
password = input("Type your password and press enter:")
message = """\
Subject: Hi there

This message is sent from Python."""

context = ssl.create_default_context()
with smtplib.SMTP(smtp_server, port) as server:
    server.ehlo()  # Can be omitted
    server.starttls(context=context)
    server.ehlo()  # Can be omitted
    server.login(sender_email, password)
    server.sendmail(sender_email, receiver_email, message)

provided thanks to the real python tutorial.


问:
Suppress unused warnings in a particular scope
In Scala (2.12) when writing a trait I have added a default implementation that can be overridden by some subclasses. Since throughout my entire implementation the state is required almost everywhere it's implicit such that I don't have to pass it every time it's required.

Considering the following code snippet, the compiler does complain that the implicit parameter state of SomeTrait.defaultMethod remains unused and throws an error. Is there any option to suppress this kind of error in that particular scope? I definitely want to keep the unused errors globally.

trait SomeTrait {

  def defaultMethod(implicit state: State) : Unit = {
     // default implemenation does nothing
  }
}

class Subclass extends SomeTrait{

 override def deafultMethod(implicit state: State) : Unit = {
    state.addInformation()
 }
}
```

Also, I would like to keep the state implicit. In theory, it's possible to add a fake usage to the method but that's not a clean solution.

答:
Scala 2.13 introduced @unused annotation

This annotation is useful for suppressing warnings under -Xlint.
  (#7623)

Here are few examples

```<code>// scalac: -Xfatal-warnings -Ywarn-unused

import annotation.unused

class X {
  def f(@unused x: Int) = 42       // no warn

  def control(x: Int) = 42         // warn to verify control

  private class C                  // warn
  @unused private class D          // no warn

  private val Some(y) = Option(42) // warn
  @unused private val Some(z) = Option(42) // no warn

  @unused("not updated") private var i = 42       // no warn
  def g = i

  @unused("not read") private var j = 42       // no warn
  def update() = j = 17
}
</code>```

Body:
In Scala (2.12) when writing a trait I have added a default implementation that can be overridden by some subclasses. Since throughout my entire implementation the state is required almost everywhere it's implicit such that I don't have to pass it every time it's required.

Considering the following code snippet, the compiler does complain that the implicit parameter state of SomeTrait.defaultMethod remains unused and throws an error. Is there any option to suppress this kind of error in that particular scope? I definitely want to keep the unused errors globally.

trait SomeTrait {

  def defaultMethod(implicit state: State) : Unit = {
     // default implemenation does nothing
  }
}

class Subclass extends SomeTrait{

 override def deafultMethod(implicit state: State) : Unit = {
    state.addInformation()
 }
}

Also, I would like to keep the state implicit. In theory, it's possible to add a fake usage to the method but that's not a clean solution.

Body:
Scala 2.13 introduced @unused annotation

This annotation is useful for suppressing warnings under -Xlint.
  (#7623)

Here are few examples

// scalac: -Xfatal-warnings -Ywarn-unused

import annotation.unused

class X {
  def f(@unused x: Int) = 42       // no warn

  def control(x: Int) = 42         // warn to verify control

  private class C                  // warn
  @unused private class D          // no warn

  private val Some(y) = Option(42) // warn
  @unused private val Some(z) = Option(42) // no warn

  @unused("not updated") private var i = 42       // no warn
  def g = i

  @unused("not read") private var j = 42       // no warn
  def update() = j = 17
}


问:
Add text on right of shinydashboard header
How do I add text to the right of a dashboard header sidebar icon? It seems that previous similar solutions no longer work under updates to dashboardHeader().

This is what I am trying to do in a basic shinydashboard setting:

I can use the strategy from this answer to get text in the header, but it's right-justified (which I can likely fix custom css) and also feels pretty hacky.

```<code>library(shiny)
library(shinydashboard)
ui <- dashboardPage(dashboardHeader(title = "demo",
  tags$li(class = "dropdown",
    tags$p("foo")
  )
), dashboardSidebar(), dashboardBody())
server <- function(input, output) { }
shinyApp(ui, server)
</code>```

Is there a better way to do this?

答:
Adding the padding properties can be a possible fix. Other options such as width, border and margin can be explored based on your requirements.

```<code>library(shiny)
library(shinydashboard)
ui <- dashboardPage(dashboardHeader(title = "demo",
                                    tags$li(class = "dropdown",
                                            style = "padding: 10px 1200px 0px 0px;",
                                            tags$p("foo")
                                    )
), dashboardSidebar(), dashboardBody())
server <- function(input, output) { }
shinyApp(ui, server)
</code>```

Hope this helps!

Body:
How do I add text to the right of a dashboard header sidebar icon? It seems that previous similar solutions no longer work under updates to dashboardHeader().

This is what I am trying to do in a basic shinydashboard setting:

I can use the strategy from this answer to get text in the header, but it's right-justified (which I can likely fix custom css) and also feels pretty hacky.

library(shiny)
library(shinydashboard)
ui <- dashboardPage(dashboardHeader(title = "demo",
  tags$li(class = "dropdown",
    tags$p("foo")
  )
), dashboardSidebar(), dashboardBody())
server <- function(input, output) { }
shinyApp(ui, server)

Is there a better way to do this?

Body:
Adding the padding properties can be a possible fix. Other options such as width, border and margin can be explored based on your requirements.

library(shiny)
library(shinydashboard)
ui <- dashboardPage(dashboardHeader(title = "demo",
                                    tags$li(class = "dropdown",
                                            style = "padding: 10px 1200px 0px 0px;",
                                            tags$p("foo")
                                    )
), dashboardSidebar(), dashboardBody())
server <- function(input, output) { }
shinyApp(ui, server)

Hope this helps!


问:
Program that reads other .py
I am coding a Python program to be able to read another .py file and make a report of its content.
The data that I need is related to the libraries, functions and variables used in that .py.
I tried to use inspect library but this requires to import that .py and I can't see all its globals.

Is there a library to perform in a better way this task?

答:
Considering @gillu13's reply, you could also use the open() function and then the built-in compile() function to retrieve a code object, on which you could base your report:</p>

```<code>code_obj = compile(file_contents, "somefilename", "eval")
</code>```

Title: Program that reads other .py

Body:
Considering @gillu13's reply, you could also use the open() function and then the built-in compile() function to retrieve a code object, on which you could base your report:

code_obj = compile(file_contents, "somefilename", "eval")


问:
How can I get (query string) parameters from the URL in Next.js?
When I click on a link in my /index.js, it brings me to /about.js page.

However, when I'm passing parameter name through URL (like /about?name=leangchhean) from /index.js to /about.js, I don't know how to get it in the /about.js page.

index.js

import Link from 'next/link';
export default () => (

    Click{' '}
    <Link href={{ pathname: 'about', query: { name: 'leangchhean' } }}>
      here
    </Link>{' '}
    to read more

);
```

答:
```<code>import { useRouter } from 'next/router';

function componentName() {
    const router = useRouter();
    console.log('router obj', router);
}
</code>```

We can find the query object inside a router using which we can get all query string parameters.

Body:
import { useRouter } from 'next/router';

function componentName() {
    const router = useRouter();
    console.log('router obj', router);
}

We can find the query object inside a router using which we can get all query string parameters.


问:
Copy with Dockerfile
I try to run the Angular app inside docker with Nginx:

```<code>$ ls
dist  Dockerfile
</code>```

Dockerfile:

```<code>FROM nginx

COPY ./dist/statistic-ui /usr/share/nginx/html/
</code>```

Inside dist/statistic-ui/ all app files.

But COPY command doesn't work, Nginx just starts with default welcome page and when I check files inside /usr/share/nginx/html/ only default Nginx files.

Why COPY command doesn't work and how to fix it?

UPDATE
Run docker container

```<code>sudo docker run -d --name ui -p 8082:80 nginx
</code>```

答:
You need to build an image from your Dockerfile then run a container from that image:

```<code>docker build -t angularapp .
docker run -d --name ui -p 8082:80 angularapp
</code>```

Make sure you include the trailing dot at the end of the docker build command.

Title: Copy with Dockerfile

Body:
I try to run the Angular app inside docker with Nginx:

$ ls
dist  Dockerfile

Dockerfile:

FROM nginx

COPY ./dist/statistic-ui /usr/share/nginx/html/

Inside dist/statistic-ui/ all app files.

But COPY command doesn't work, Nginx just starts with default welcome page and when I check files inside /usr/share/nginx/html/ only default Nginx files.

Why COPY command doesn't work and how to fix it?

UPDATE
Run docker container

sudo docker run -d --name ui -p 8082:80 nginx

Body:
You need to build an image from your Dockerfile then run a container from that image:

docker build -t angularapp .
docker run -d --name ui -p 8082:80 angularapp

Make sure you include the trailing dot at the end of the docker build command.


问:
string value obtained from reading from json file , displays weirdly when using Path.Combine
I have a functionality where I would scan a given path for a certain file and process some information based on the information in that file . this file info.json in json syntax has a name and a relative path to a certain  directory .
What I am trying to do is simply obtain the relative path from the json file and print out an absoulute path

the relative file specified in the info.json file is as below,

```<code>{
  "Name": "testName",
  "OriginalPath": "new/File"
}
</code>```

The absolute path that I am trying to print out is something like :- D:\testDel\new\File but the actual value is always something like D:\testDel\new/File , while I must say this path is still a valid path (when I do a win key + R I can navigate to that directory) but in terms of how its been displayed it looks messy .

Any Idea as to why I might be facing this problem , am I doing something wrong ,

my code is as follows

```<code>string path = @"D:\testDel";
            IEnumerable<string> foundFiles = Directory.EnumerateFiles(path, "info.json", SearchOption.AllDirectories);

            foreach (string file in foundFiles)
            {

                DataModel data = JsonConvert.DeserializeObject<DataModel>(File.ReadAllText(file));

                string Name = data.Name;
                string absolutePath = data.OriginalPath;
                string folderpath = Path.GetDirectoryName(file);
                string fullPath = Path.Combine(folderpath, absolutePath);
                Console.WriteLine(fullPath);

            }
    public class DataModel
    {
        public string Name { get; set; }
        public string OriginalPath { get; set; }
    }
</code>```

答:
Wrap the Path.Combine(folderpath, absolutePath) statement in a Path.GetFullPath() as

```<code>fullPath=Path.GetFullPath(Path.Combine(folderpath, absolutePath));
</code>```

this will also resolve reletive paths like ../NewFil to D:\NewFile

Body:
I have a functionality where I would scan a given path for a certain file and process some information based on the information in that file . this file info.json in json syntax has a name and a relative path to a certain  directory .
What I am trying to do is simply obtain the relative path from the json file and print out an absoulute path

the relative file specified in the info.json file is as below,

{
  "Name": "testName",
  "OriginalPath": "new/File"
}

The absolute path that I am trying to print out is something like :- D:\testDel\new\File but the actual value is always something like D:\testDel\new/File , while I must say this path is still a valid path (when I do a win key + R I can navigate to that directory) but in terms of how its been displayed it looks messy .

Any Idea as to why I might be facing this problem , am I doing something wrong ,

my code is as follows

string path = @"D:\testDel";
            IEnumerable<string> foundFiles = Directory.EnumerateFiles(path, "info.json", SearchOption.AllDirectories);

            foreach (string file in foundFiles)
            {

                DataModel data = JsonConvert.DeserializeObject<DataModel>(File.ReadAllText(file));

                string Name = data.Name;
                string absolutePath = data.OriginalPath;
                string folderpath = Path.GetDirectoryName(file);
                string fullPath = Path.Combine(folderpath, absolutePath);
                Console.WriteLine(fullPath);

            }
    public class DataModel
    {
        public string Name { get; set; }
        public string OriginalPath { get; set; }
    }

Body:
Wrap the Path.Combine(folderpath, absolutePath) statement in a Path.GetFullPath() as

fullPath=Path.GetFullPath(Path.Combine(folderpath, absolutePath));

this will also resolve reletive paths like ../NewFil to D:\NewFile


问:
Can't change promise pending status after using then()
I'm trying to load a CSV file into my application at the beginning and keep the value in a variable and call it from other functions instead of accessing by then all the time

my code is

```<code>var DVizModule = (() => {

    let dataset = [];

    let _data = async () => {
        const data = await d3.csv("data/alphabet.csv");
        return data;
    }
    let data = _data().then(data => {
        dataset = data;
        return dataset;
    })

    return {
        data: data
    }
})();
console.log(DVizModule.data);
</code>```

it returns

```<code>Promise pending proto: Promise

PromiseStatus: "resolved"

PromiseValue: Array(26)
</code>```

When I write

```<code>const t = async function() {
    const data = await d3.csv("data/alphabet.csv");
    return data;
}
t().then(result => console.log(result))
</code>```

it returns the file perfectly
I'm trying to access the file content via

```<code>DVizModule.data
</code>```

答:
If you want to access data synchronously, you should declare it as a plain value, not a promise. something like this should do the trick:

```<code>const DVizModule = {};
d3.csv("data/alphabet.csv").then(data => DVizModule.data = data);
</code>```

Note, of course, that DVizModule.data will be undefined until the request is actually complete. If you want to ensure that the value actually is there, you will have to wrap the outer context into an async function and await the data at the very beginning. This way you can both ensure that the value is present when you code accesses it and use it in a synchronous manner.

Hope I got your question right and not trying to resolve the wrong problem ;)

Body:
I'm trying to load a CSV file into my application at the beginning and keep the value in a variable and call it from other functions instead of accessing by then all the time

my code is

var DVizModule = (() => {

    let dataset = [];

    let _data = async () => {
        const data = await d3.csv("data/alphabet.csv");
        return data;
    }
    let data = _data().then(data => {
        dataset = data;
        return dataset;
    })

    return {
        data: data
    }
})();
console.log(DVizModule.data);

it returns

Promise pending proto: Promise

PromiseStatus: "resolved"

PromiseValue: Array(26)

When I write

const t = async function() {
    const data = await d3.csv("data/alphabet.csv");
    return data;
}
t().then(result => console.log(result))

it returns the file perfectly
I'm trying to access the file content via

DVizModule.data

Body:
If you want to access data synchronously, you should declare it as a plain value, not a promise. something like this should do the trick:

const DVizModule = {};
d3.csv("data/alphabet.csv").then(data => DVizModule.data = data);

Note, of course, that DVizModule.data will be undefined until the request is actually complete. If you want to ensure that the value actually is there, you will have to wrap the outer context into an async function and await the data at the very beginning. This way you can both ensure that the value is present when you code accesses it and use it in a synchronous manner.

Hope I got your question right and not trying to resolve the wrong problem ;)


问:
Check if array of objects key is empty and splice it
I have an array of objects, in that there is an empty key with Boolean value, if the Boolean value is false then the array of objects should be spliced.

The below is the array structure:

this.dataTobeDeleted= [{
    NotificationID: "2180",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": true
  },
  {
    NotificationID: "2182",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": false
  },
  {
    NotificationID: "2181",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": false
  }
]```
</div>
</div>
</p>

<p>In the above array there is an empty string "key" if the key value is <code>false</code> then need to splice the array of objects using index.</p>

<p>Below is the code which I have tried:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>for (var i = 0; i < this.dataTobeDeleted.length; i++) {
    for (var val in this.dataTobeDeleted[i]) {
      if (val === "") {

        this.dataTobeDeleted[i]['isCheckedValue'] = this.dataTobeDeleted[i][""]; // insetring new key for empty key string
        delete this.dataTobeDeleted[i][""]; // Delete old key
        if (this.dataTobeDeleted[i].isCheckedValue === false) {
          this.dataTobeDeleted.splice(i, 1)
        }
      }
    }
}</code>```

The above code is correct, but I need it in shorter way as the code I tried is in lengthier and when there is too much data it will create a problem.

I tried using filter also, but I am not getting the empty key to check the boolean value.

答:
Quoting from MDN on Object.keys():

The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.

Then you can find the empty key and remove it with the delete method.

```<code>const deletedData = dataTobeDeleted.map((item, index) => {
    Object.keys(item).map(key => {
        if (!item['']) {
            dataTobeDeleted.splice(index, 1);
        }
    });
});
</code>```

Body:
I have an array of objects, in that there is an empty key with Boolean value, if the Boolean value is false then the array of objects should be spliced.

The below is the array structure:

this.dataTobeDeleted= [{
    NotificationID: "2180",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": true
  },
  {
    NotificationID: "2182",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": false
  },
  {
    NotificationID: "2181",
    Quantity: 1,
    NotificationName: "453",
    AlertNumber: "02/19/2020",
    "": false
  }
]

In the above array there is an empty string "key" if the key value is false then need to splice the array of objects using index.

Below is the code which I have tried:

for (var i = 0; i < this.dataTobeDeleted.length; i++) {
    for (var val in this.dataTobeDeleted[i]) {
      if (val === "") {

        this.dataTobeDeleted[i]['isCheckedValue'] = this.dataTobeDeleted[i][""]; // insetring new key for empty key string
        delete this.dataTobeDeleted[i][""]; // Delete old key
        if (this.dataTobeDeleted[i].isCheckedValue === false) {
          this.dataTobeDeleted.splice(i, 1)
        }
      }
    }
}

The above code is correct, but I need it in shorter way as the code I tried is in lengthier and when there is too much data it will create a problem.

I tried using filter also, but I am not getting the empty key to check the boolean value.

Body:
Quoting from MDN on Object.keys():

The Object.keys() method returns an array of a given object's own enumerable property names, iterated in the same order that a normal loop would.

Then you can find the empty key and remove it with the delete method.

const deletedData = dataTobeDeleted.map((item, index) => {
    Object.keys(item).map(key => {
        if (!item['']) {
            dataTobeDeleted.splice(index, 1);
        }
    });
});


问:
Conflict Newtonsoft.Json 6.0.0.0 and 12.0.0.0 in Web Application with Web Api, C#
I have started a new Web Application in Visual Studio 2019. I have added a Web Api. Shortly after or at the same time (can't remember), I startet getting warnings like this:

```<code>Warning     No way to resolve conflict between "Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed" and "Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed". Choosing "Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed" arbitrarily.
</code>```

I noticed but did not do anything as I decided to wait until it gave me problems.

And that is now...

I am about to use a JSon object but when writing this:

```<code>JObject jObject = JObject.Parse(result);
</code>```

The compiler gives me this error:

```<code>Error   CS0433  The type 'JObject' exists in both 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' and 'Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'
</code>```

I have searched the web and my conclusions are as follows:

It looks like it is Microsoft.AspNet.WebApi.Client that is the only package installed, that has a dependency on Newtonsoft.Json (>= 6.0.4)

I have installed Newtonsoft.Json (12.0.3)

In Solution Explorer. In reference list, I have only 1 reference. And that is the one for 12.0.3.

In Web.Config I have this entry (and only this for Newtonsoft.Json).

<dependentAssembly><assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30AD4FE6B2A6AEED" culture="neutral"/><bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0"/></dependentAssembly>

In my .csproj I can see 3 different references in 3 different ItemGroups:

One for v. 12.0.0.0

One for v. 12.0.2

And one for v. 12.0.3

I tried to uninstall package Newtonsoft.Json, but is not allowed as other packages are dependent on this.

I have runned this command: Update-Package Newtonsoft.Json in the Package Manager Console, which told me, that no new updates were available.

And now, I have runned out of ideas. I am stucked. Anyone knows what to do?

****New update****
I found the 6.0.0.0. Please have a look at the picture:

Here in resources I double clicked the Newtonsoft.Json reference and in the object browser I can see both 6.0.0.0 and 12.0.0.0.

As you can see, both 6.0.0.0 and 12.0.0.0 are present. 6.0.0.0 is somewhere on my C:-drive inside a SDK.

I have tried to delete the file. My project got nuts. Then I replaced that file with the 12.0.0.0 from my project. This gave me the error that assemplies did not match.

I finally copied the old .dll back. And is a bit stucked again.

Any ideas?

答:
Okay, I fixed it.

I had 2 references in my .csproj file to Newtonsoft.Json. One pointed at packages......\xxx.12.0.3 and one pointing at packages......\xxx.12.0.2.

Both of them was above 6.0.0.0 which was the error I got. So I ignored them.

But acutally, in my project I had only 12.0.3 folder and no 12.0.2 folder. So the reference did not work and VS tried to find another place to look.

I guess it looks around, maybe using the GAC but finally it ended up deep down my local drive in one Azure SDK and found Newtonsoft.Json 6.0.0.0. And that was the problem.

I removed the 12.0.2 reference from my .csproj and finally it worked.

Body:
I have started a new Web Application in Visual Studio 2019. I have added a Web Api. Shortly after or at the same time (can't remember), I startet getting warnings like this:

Warning     No way to resolve conflict between "Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed" and "Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed". Choosing "Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed" arbitrarily.

I noticed but did not do anything as I decided to wait until it gave me problems.

And that is now...

I am about to use a JSon object but when writing this:

JObject jObject = JObject.Parse(result);

The compiler gives me this error:

Error   CS0433  The type 'JObject' exists in both 'Newtonsoft.Json, Version=6.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' and 'Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'

I have searched the web and my conclusions are as follows:

It looks like it is Microsoft.AspNet.WebApi.Client that is the only package installed, that has a dependency on Newtonsoft.Json (>= 6.0.4)

I have installed Newtonsoft.Json (12.0.3)

In Solution Explorer. In reference list, I have only 1 reference. And that is the one for 12.0.3.

In Web.Config I have this entry (and only this for Newtonsoft.Json).

<dependentAssembly><assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30AD4FE6B2A6AEED" culture="neutral"/><bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0"/></dependentAssembly>

In my .csproj I can see 3 different references in 3 different ItemGroups:

One for v. 12.0.0.0

One for v. 12.0.2

And one for v. 12.0.3

I tried to uninstall package Newtonsoft.Json, but is not allowed as other packages are dependent on this.

I have runned this command: Update-Package Newtonsoft.Json in the Package Manager Console, which told me, that no new updates were available.

And now, I have runned out of ideas. I am stucked. Anyone knows what to do?

****New update****
I found the 6.0.0.0. Please have a look at the picture:

Here in resources I double clicked the Newtonsoft.Json reference and in the object browser I can see both 6.0.0.0 and 12.0.0.0.

As you can see, both 6.0.0.0 and 12.0.0.0 are present. 6.0.0.0 is somewhere on my C:-drive inside a SDK.

I have tried to delete the file. My project got nuts. Then I replaced that file with the 12.0.0.0 from my project. This gave me the error that assemplies did not match.

I finally copied the old .dll back. And is a bit stucked again.

Any ideas?


问:
How to check if current time falls within a specific range on a week day using jquery/javascript?
When a user visits a page I need to check if the current time falls between 9:00 am and 5:30pm on a weekday and display something using jquery/javascript.But I am not sure how can check that.

Could someone please help?

Thanks

答:
I had a requirement where I needed to find if time in one date object lies within other two. (Date didn't matter, instead only time).

I did it this way, I thought it might help someone.

```<code>/*
* d, start and end all are Date objects.
*/
const checkIfTimeIsInRange = (d, start, end) => {
    if (start.getHours() < d.getHours() && d.getHours() < end.getHours()) {
        return true;
    } else if (start.getHours() == d.getHours()) {
        if (d.getHours() == end.getHours()) {
            if(start.getMinutes() <= d.getMinutes() && d.getMinutes() <= end.getMinutes()) {
                return true
            } else {
                return false
            }
        } else if(start.getMinutes() <= d.getMinutes()) {
            return true
        } else {
            return false
        }
    } else if (d.getHours() == end.getHours()) {
        if(d.getMinutes() <= end.getMinutes()) {
            return true
        } else {
            return false
        }
    } else {
        return false
    }
}
</code>```

P.S. Any improvements, suggestions are welcome.

Body:
I had a requirement where I needed to find if time in one date object lies within other two. (Date didn't matter, instead only time).

I did it this way, I thought it might help someone.

/*
* d, start and end all are Date objects.
*/
const checkIfTimeIsInRange = (d, start, end) => {
    if (start.getHours() < d.getHours() && d.getHours() < end.getHours()) {
        return true;
    } else if (start.getHours() == d.getHours()) {
        if (d.getHours() == end.getHours()) {
            if(start.getMinutes() <= d.getMinutes() && d.getMinutes() <= end.getMinutes()) {
                return true
            } else {
                return false
            }
        } else if(start.getMinutes() <= d.getMinutes()) {
            return true
        } else {
            return false
        }
    } else if (d.getHours() == end.getHours()) {
        if(d.getMinutes() <= end.getMinutes()) {
            return true
        } else {
            return false
        }
    } else {
        return false
    }
}

P.S. Any improvements, suggestions are welcome.


问:
Unicode and incorrect number of arguments errors with Python 3 and MySQL connector
I'm trying to execute a simple SELECT query on a MySQL(MariaDB) database in Python 3.

I'm getting very weird errors

        query = (
            'SELECT user_id, user_password_hash, user_password_salt '
            'FROM users '
            'WHERE user_username = "%s"'
        )

        print(f'Trying login, username {username}, password {password}')

        try:
            cursor = self.connection.cursor(prepared=True)
            cursor.execute(query, (username,))

            results = cursor.fetchone()

            print(results)
            ...

        except Error as e:
            print('Error in login query: ' + str(e))
            raise e
```

<p>Running this code gives me the following error:
<code>Error in login query: 1210: Incorrect number of arguments executing prepared statement</code></p>

<p>I don't understand - it requires one argument, and I've given it one argument.
Removing the comma in the tuple in <code>execute()</code> doesn't fix this problem.</p>

<p>Now, if I remove the quotes from the query, I get an entirely different error:</p>

<pre class="lang-py prettyprint-override"><code>        query = (
            'SELECT user_id, user_password_hash, user_password_salt '
            'FROM users '
            'WHERE user_username = %s'
        )
</code>```

```<code>UnicodeDecodeError: 'utf-8' codec can't decode byte 0x9b in position 0: invalid start byte

The above exception was the direct cause of the following exception:

SystemError: <class 'UnicodeDecodeError'> returned a result with an error set
</code>```

The table is using utf8mb4, so that shouldn't be a problem.

Also, running SELECT * FROM users WHERE user_username="jeff" in the MySQL console works fine.

This should be a really trivial query, but I've got absolutely no idea what's going on - any help would be greatly appreciated.

EDIT: When experimenting in an isolated Python process, I reproduced the problem by running this:

import mysql.connector

conn = mysql.connector.connect(host="localhost",
                               database="lucidlab",
                               user="lucidlab",
                               password="lucidlab")

cur = conn.cursor()
cur.execute("SELECT * FROM users WHERE user_username='jeff'")

results = cur.fetchall() # ERROR
print(results)
```

This makes me think that perhaps it's a database encoding problem?

EDIT: I've solved the problem. Please see my answer below.

答:
Try using double quotation marks:

```<code>    query = ("SELECT user_id, user_password_hash, user_password_salt "
        "FROM users "
        "WHERE user_username = %s"
    )
</code>```

or tripple quotations:

```<code>    query = ("""SELECT user_id, user_password_hash, user_password_salt
        FROM users
        WHERE user_username = %s"""
    )
</code>```

Body:
I'm trying to execute a simple SELECT query on a MySQL(MariaDB) database in Python 3.

I'm getting very weird errors

        query = (
            'SELECT user_id, user_password_hash, user_password_salt '
            'FROM users '
            'WHERE user_username = "%s"'
        )

        print(f'Trying login, username {username}, password {password}')

        try:
            cursor = self.connection.cursor(prepared=True)
            cursor.execute(query, (username,))

            results = cursor.fetchone()

            print(results)
            ...

        except Error as e:
            print('Error in login query: ' + str(e))
            raise e

Running this code gives me the following error:
Error in login query: 1210: Incorrect number of arguments executing prepared statement

I don't understand - it requires one argument, and I've given it one argument.
Removing the comma in the tuple in execute() doesn't fix this problem.

Now, if I remove the quotes from the query, I get an entirely different error:

        query = (
            'SELECT user_id, user_password_hash, user_password_salt '
            'FROM users '
            'WHERE user_username = %s'
        )

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x9b in position 0: invalid start byte

The above exception was the direct cause of the following exception:

SystemError: <class 'UnicodeDecodeError'> returned a result with an error set

The table is using utf8mb4, so that shouldn't be a problem.

Also, running SELECT * FROM users WHERE user_username="jeff" in the MySQL console works fine.

This should be a really trivial query, but I've got absolutely no idea what's going on - any help would be greatly appreciated.

EDIT: When experimenting in an isolated Python process, I reproduced the problem by running this:

import mysql.connector

conn = mysql.connector.connect(host="localhost",
                               database="lucidlab",
                               user="lucidlab",
                               password="lucidlab")

cur = conn.cursor()
cur.execute("SELECT * FROM users WHERE user_username='jeff'")

results = cur.fetchall() # ERROR
print(results)

This makes me think that perhaps it's a database encoding problem?

EDIT: I've solved the problem. Please see my answer below.

Body:
Try using double quotation marks:

    query = ("SELECT user_id, user_password_hash, user_password_salt "
        "FROM users "
        "WHERE user_username = %s"
    )

or tripple quotations:

    query = ("""SELECT user_id, user_password_hash, user_password_salt
        FROM users
        WHERE user_username = %s"""
    )


问:
Unable to upload/download blob storage to container from local environment
I have an exiting functions app that has the functionality to download a file from sftp, process the file and upload file to blob storage. This functions app is already deployed in azure and working properly. However, when I run the same thing from visual studio (local) I get error at uploading file to blob storage.

Microsoft.Azure.Storage.StorageException: This request is not authorized to perform this operation using this permission.

I made sure this app has the necessary contributor role assigned in a storage account (thats why its working from azure). Are there any other settings I need to configure in local settings or project settings for these functions to work same like when they are deployed to azure? Or could there be any settings in storage account that is overriding to perform upload operation when run from dev but run only from azure?

I made sure I use local settings have all are copied from app configuration which has storage account names, connection string of blob storage, sftp url, and key vault name which has credetails of sft site etc.,

Update:
Forgot to mention that az storage container upload command from command-line from my machine uploaded file successfully.

update2:
As per suggested by I have followed the tutorial and I was successfully able to create the container, upload blob and do cleanup without errors.
Then I consolidated code to simulate simple download blob into memory stream which is also throwing error

This request is not authorized to perform this operation using this
  permission
  (see full log in the bottom)

Code to download blob:

```<code>static async Task TokenCredentialsSample()
{
    var tenantId = "xxxxx-xxxx-xxxx-xxxx-xxxxxxxx";
    var tokenProvider = new AzureServiceTokenProvider().GetAccessTokenAsync("https://storage.azure.com/",tenantId);
    var tokenCredential = new TokenCredential(tokenProvider.Result);
    var storageCredentials = new StorageCredentials(tokenCredential);
    var uri = new Uri("https://mystorageaccount.blob.core.windows.net/mycontainer/inbound/myfile.csv");

    var cloudBlockBlob = new CloudBlockBlob(uri, storageCredentials);

    var memoryStream = new MemoryStream();

    cloudBlockBlob.DownloadToStream(memoryStream); // Error here
    memoryStream.Position = 0;
    memoryStream.Close();

}
</code>```

I have also made sure I typed az login from command-line to switch to select correct subscription and also the account is selected in visual studio options.

Error log:

Microsoft.Azure.Storage.StorageException
  HResult=0x80131500
  Message=This request is not authorized to perform this operation using this permission.
  Source=Microsoft.Azure.Storage.Common
  StackTrace:
   at Microsoft.Azure.Storage.Core.Executor.Executor.d__11.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
   at Microsoft.Azure.Storage.Core.Executor.Executor.<>c__DisplayClass0_01.<ExecuteSync>b__0()
   at Microsoft.Azure.Storage.Core.Util.CommonUtility.RunWithoutSynchronizationContext[T](Func1 actionToRun)
   at Microsoft.Azure.Storage.Core.Executor.Executor.ExecuteSync[T](RESTCommand1 cmd, IRetryPolicy policy, OperationContext operationContext)
   at Microsoft.Azure.Storage.Blob.CloudBlob.DownloadRangeToStream(Stream target, Nullable1 offset, Nullable`1 length, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
   at Microsoft.Azure.Storage.Blob.CloudBlob.DownloadToStream(Stream target, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
   at BlobStorage.Program.d__2.MoveNext() in c:...\source\repos\BlobStorage\Program.cs:line 111
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at BlobStorage.Program.d__0.MoveNext() in c:...\source\repos\BlobStorage\Program.cs:line 19

This exception was originally thrown at this call stack:
    Microsoft.Azure.Storage.Core.Executor.Executor.ExecuteAsync(Microsoft.Azure.Storage.Core.Executor.RESTCommand, Microsoft.Azure.Storage.RetryPolicies.IRetryPolicy, Microsoft.Azure.Storage.OperationContext, System.Threading.CancellationToken)
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task)
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
    System.Runtime.CompilerServices.TaskAwaiter.GetResult()
    Microsoft.Azure.Storage.Core.Executor.Executor.ExecuteSync.AnonymousMethod__0()
    Microsoft.Azure.Storage.Core.Util.CommonUtility.RunWithoutSynchronizationContext(System.Func)
    Microsoft.Azure.Storage.Core.Executor.Executor.ExecuteSync(Microsoft.Azure.Storage.Core.Executor.RESTCommand, Microsoft.Azure.Storage.RetryPolicies.IRetryPolicy, Microsoft.Azure.Storage.OperationContext)
    Microsoft.Azure.Storage.Blob.CloudBlob.DownloadRangeToStream(System.IO.Stream, long?, long?, Microsoft.Azure.Storage.AccessCondition, Microsoft.Azure.Storage.Blob.BlobRequestOptions, Microsoft.Azure.Storage.OperationContext)
    Microsoft.Azure.Storage.Blob.CloudBlob.DownloadToStream(System.IO.Stream, Microsoft.Azure.Storage.AccessCondition, Microsoft.Azure.Storage.Blob.BlobRequestOptions, Microsoft.Azure.Storage.OperationContext)
    ...
    [Call Stack Truncated]

答:
1)
I see your returning a Task from your method, yet not awaiting anything.

Its a good practice to add the 'async` keyword to the method signature and change the following code:

```<code>var tokenProvider = new AzureServiceTokenProvider().GetAccessTokenAsync("https://storage.azure.com/",tenantId);
</code>```

to something like:

```<code>var tokenProvider = new AzureServiceTokenProvider();
var token = await tokenProvider.GetAccessTokenAsync("https://storage.azure.com/",tenantId);
var tokenCredential = new TokenCredential(token );
</code>```

Now, get your access token your can use a tool like http://jwt.io and crack it open and inspect the claims.

2)
Trying changing the access token from:

```<code>GetAccessTokenAsync("https://storage.azure.com/",tenantId);
</code>```

to:

```<code>GetAccessTokenAsync("https://[youraccount].blob.core.windows.net",tenantId);
</code>```

3)
The AzureServiceTokenProvider will look for credentials in a set of predefined places.

The AzureServiceTokenProvider documentation is worth reading through, to help trouble shoot.

Have you tried using the first option of passing RunAs=Developer; DeveloperTool=AzureCli as the connection string, so it explicitly knows where to look?

So, from the same command window where you executed the azure cli and did something like azure login, have you tried to run the console program from there?

Which subscription are you logged into?  az account list

Do you have many subscriptions?

Your default subscription may not be the one where you are trying to access the blob from.

Body:
I have an exiting functions app that has the functionality to download a file from sftp, process the file and upload file to blob storage. This functions app is already deployed in azure and working properly. However, when I run the same thing from visual studio (local) I get error at uploading file to blob storage.

Microsoft.Azure.Storage.StorageException: This request is not authorized to perform this operation using this permission.

I made sure this app has the necessary contributor role assigned in a storage account (thats why its working from azure). Are there any other settings I need to configure in local settings or project settings for these functions to work same like when they are deployed to azure? Or could there be any settings in storage account that is overriding to perform upload operation when run from dev but run only from azure?

I made sure I use local settings have all are copied from app configuration which has storage account names, connection string of blob storage, sftp url, and key vault name which has credetails of sft site etc.,

Update:
Forgot to mention that az storage container upload command from command-line from my machine uploaded file successfully.

update2:
As per suggested by I have followed the tutorial and I was successfully able to create the container, upload blob and do cleanup without errors.
Then I consolidated code to simulate simple download blob into memory stream which is also throwing error

This request is not authorized to perform this operation using this
  permission
  (see full log in the bottom)

Code to download blob:

static async Task TokenCredentialsSample()
{
    var tenantId = "xxxxx-xxxx-xxxx-xxxx-xxxxxxxx";
    var tokenProvider = new AzureServiceTokenProvider().GetAccessTokenAsync("https://storage.azure.com/",tenantId);
    var tokenCredential = new TokenCredential(tokenProvider.Result);
    var storageCredentials = new StorageCredentials(tokenCredential);
    var uri = new Uri("https://mystorageaccount.blob.core.windows.net/mycontainer/inbound/myfile.csv");

    var cloudBlockBlob = new CloudBlockBlob(uri, storageCredentials);

    var memoryStream = new MemoryStream();

    cloudBlockBlob.DownloadToStream(memoryStream); // Error here
    memoryStream.Position = 0;
    memoryStream.Close();

}

I have also made sure I typed az login from command-line to switch to select correct subscription and also the account is selected in visual studio options.

Error log:

Microsoft.Azure.Storage.StorageException
  HResult=0x80131500
  Message=This request is not authorized to perform this operation using this permission.
  Source=Microsoft.Azure.Storage.Common
  StackTrace:
   at Microsoft.Azure.Storage.Core.Executor.Executor.d__11.MoveNext()
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
   at Microsoft.Azure.Storage.Core.Executor.Executor.<>c__DisplayClass0_01.<ExecuteSync>b__0()
   at Microsoft.Azure.Storage.Core.Util.CommonUtility.RunWithoutSynchronizationContext[T](Func1 actionToRun)
   at Microsoft.Azure.Storage.Core.Executor.Executor.ExecuteSync[T](RESTCommand1 cmd, IRetryPolicy policy, OperationContext operationContext)
   at Microsoft.Azure.Storage.Blob.CloudBlob.DownloadRangeToStream(Stream target, Nullable1 offset, Nullable`1 length, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
   at Microsoft.Azure.Storage.Blob.CloudBlob.DownloadToStream(Stream target, AccessCondition accessCondition, BlobRequestOptions options, OperationContext operationContext)
   at BlobStorage.Program.d__2.MoveNext() in c:...\source\repos\BlobStorage\Program.cs:line 111
   at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
   at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
   at BlobStorage.Program.d__0.MoveNext() in c:...\source\repos\BlobStorage\Program.cs:line 19

This exception was originally thrown at this call stack:
    Microsoft.Azure.Storage.Core.Executor.Executor.ExecuteAsync(Microsoft.Azure.Storage.Core.Executor.RESTCommand, Microsoft.Azure.Storage.RetryPolicies.IRetryPolicy, Microsoft.Azure.Storage.OperationContext, System.Threading.CancellationToken)
    System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(System.Threading.Tasks.Task)
    System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(System.Threading.Tasks.Task)
    System.Runtime.CompilerServices.TaskAwaiter.GetResult()
    Microsoft.Azure.Storage.Core.Executor.Executor.ExecuteSync.AnonymousMethod__0()
    Microsoft.Azure.Storage.Core.Util.CommonUtility.RunWithoutSynchronizationContext(System.Func)
    Microsoft.Azure.Storage.Core.Executor.Executor.ExecuteSync(Microsoft.Azure.Storage.Core.Executor.RESTCommand, Microsoft.Azure.Storage.RetryPolicies.IRetryPolicy, Microsoft.Azure.Storage.OperationContext)
    Microsoft.Azure.Storage.Blob.CloudBlob.DownloadRangeToStream(System.IO.Stream, long?, long?, Microsoft.Azure.Storage.AccessCondition, Microsoft.Azure.Storage.Blob.BlobRequestOptions, Microsoft.Azure.Storage.OperationContext)
    Microsoft.Azure.Storage.Blob.CloudBlob.DownloadToStream(System.IO.Stream, Microsoft.Azure.Storage.AccessCondition, Microsoft.Azure.Storage.Blob.BlobRequestOptions, Microsoft.Azure.Storage.OperationContext)
    ...
    [Call Stack Truncated]

Body:
1)
I see your returning a Task from your method, yet not awaiting anything.

Its a good practice to add the 'async` keyword to the method signature and change the following code:

var tokenProvider = new AzureServiceTokenProvider().GetAccessTokenAsync("https://storage.azure.com/",tenantId);

to something like:

var tokenProvider = new AzureServiceTokenProvider();
var token = await tokenProvider.GetAccessTokenAsync("https://storage.azure.com/",tenantId);
var tokenCredential = new TokenCredential(token );

Now, get your access token your can use a tool like http://jwt.io and crack it open and inspect the claims.

2)
Trying changing the access token from:

GetAccessTokenAsync("https://storage.azure.com/",tenantId);

to:

GetAccessTokenAsync("https://[youraccount].blob.core.windows.net",tenantId);

3)
The AzureServiceTokenProvider will look for credentials in a set of predefined places.

The AzureServiceTokenProvider documentation is worth reading through, to help trouble shoot.

Have you tried using the first option of passing RunAs=Developer; DeveloperTool=AzureCli as the connection string, so it explicitly knows where to look?

So, from the same command window where you executed the azure cli and did something like azure login, have you tried to run the console program from there?

Which subscription are you logged into?  az account list

Do you have many subscriptions?

Your default subscription may not be the one where you are trying to access the blob from.


问:
Getting Semester Averages with Grades using files in Python
I want to write code that will take a file of grades and return an average of it all, so homework average, project average, quiz average, and semester average. In the file it would have a column at the start which would be the "legend" to the code. Here's an example of what the grade file would look like:

```<code>last, first, hw, hw, project, quiz, hw, hw, hw, quiz, hw, hw, project
#It won't also be in this order, that's what makes this hard!
Cat, Figaro, 57, 58, 71, 93, 56, 86, 90, 99, 55, 99, 88
#Not a real name lol, there would also be A LOT more names and grades
</code>```

I can't figure out how to make it iterate through the legend column and the grades column to correctly grade the file. Here's the formula for grading:

```<code>semester average = homework average * 0.2 + quiz average * 0.2 + project average * 0.6.
</code>```

Here's what I have so far. I'm terrible with files so I only know how to call a column.

```<code>def start():
  gb_data = open('gb_data.txt','r')
  header = gb_data.readline()
  print(header.strip())
</code>```

the strip() at the end would get rid of the \n that happens when you change lines. This prints the first column of the file but I want to iterate through it and identify the legend, not just print it. Here's what the return file would look like:

```<code>Cat, Figaro: hw avg = 71.57, quiz avg = 96.0, proj avg = 79.5, sem avg = 81.21
</code>```

Please help! This is NOT homework and is simply a project to understand files better, my name is Scarlett btw.

答:
EDIT This code is incorrect for multiple rows

You could try the following code:

```<code>def start():
    with open('gb_data_.txt', 'r') as f:
        keys = f.readline().strip().split(',')
        values = f.readline().strip().split(',')
        last = values[0]
        first = values[1]

        hw = [int(v) for k, v in zip(keys, values) where 'hw' in k]
        hw_avr = sum(hw) / len(hw)

        project = [int(v) for k, v in zip(keys, values) where 'project' in k]
        project_avr = sum(project) / len(project)

        quiz = [int(v) for k, v in zip(keys, values) where 'quiz' in k]
        quiz_avr = sum(quiz) / len(quiz)

        sem_avr = hw_avr * 0.2 + quiz_avr * 0.2 + project_avr * 0.2
</code>```

Body:
I want to write code that will take a file of grades and return an average of it all, so homework average, project average, quiz average, and semester average. In the file it would have a column at the start which would be the "legend" to the code. Here's an example of what the grade file would look like:

last, first, hw, hw, project, quiz, hw, hw, hw, quiz, hw, hw, project
#It won't also be in this order, that's what makes this hard!
Cat, Figaro, 57, 58, 71, 93, 56, 86, 90, 99, 55, 99, 88
#Not a real name lol, there would also be A LOT more names and grades

I can't figure out how to make it iterate through the legend column and the grades column to correctly grade the file. Here's the formula for grading:

semester average = homework average * 0.2 + quiz average * 0.2 + project average * 0.6.

Here's what I have so far. I'm terrible with files so I only know how to call a column.

def start():
  gb_data = open('gb_data.txt','r')
  header = gb_data.readline()
  print(header.strip())

the strip() at the end would get rid of the \n that happens when you change lines. This prints the first column of the file but I want to iterate through it and identify the legend, not just print it. Here's what the return file would look like:

Cat, Figaro: hw avg = 71.57, quiz avg = 96.0, proj avg = 79.5, sem avg = 81.21

Please help! This is NOT homework and is simply a project to understand files better, my name is Scarlett btw.

Body:
EDIT This code is incorrect for multiple rows

You could try the following code:

def start():
    with open('gb_data_.txt', 'r') as f:
        keys = f.readline().strip().split(',')
        values = f.readline().strip().split(',')
        last = values[0]
        first = values[1]

        hw = [int(v) for k, v in zip(keys, values) where 'hw' in k]
        hw_avr = sum(hw) / len(hw)

        project = [int(v) for k, v in zip(keys, values) where 'project' in k]
        project_avr = sum(project) / len(project)

        quiz = [int(v) for k, v in zip(keys, values) where 'quiz' in k]
        quiz_avr = sum(quiz) / len(quiz)

        sem_avr = hw_avr * 0.2 + quiz_avr * 0.2 + project_avr * 0.2


问:
Can I upgrade Elasticache Redis Engine Version without downtime?
I cannot find any information in the AWS documentation that modifying the Redis engine version will or will not cause downtime. It does not explain how the upgrade occurs other than it's performed in the maintenance window.

It is safe to upgrade a production Elasticache Redis instance via the AWS console without loss of data or downtime?

Note: The client library we use is compatible with all versions of Redis so the application should not notice the upgrade.

答:
As mentioned by Will above, the AWS answer has changed. and in theory you can do it without downtime. See:

https://docs.aws.amazon.com/AmazonElastiCache/latest/red-ug/VersionManagement.html

The key points are in terms of downtime and impact on existing use:

The Amazon ElastiCache for Redis engine upgrade process is designed
  to make a best effort to retain your existing data and requires
  successful Redis replication.

...

For single Redis clusters and clusters with Multi-AZ disabled, we
  recommend that sufficient memory be made available to Redis as
  described in Ensuring That You Have Enough Memory to Create a Redis
  Snapshot. In these cases, the primary is unavailable to service
  requests during the upgrade process.

...

For Redis clusters with Multi-AZ enabled, we also recommend that you
  schedule engine upgrades during periods of low incoming write traffic.
  When upgrading to Redis 5.0.5 or above, the primary cluster continues
  to be available to service requests during the upgrade process. When
  upgrading to Redis 5.0.4 or below, you may notice a brief interruption
  of a few seconds associated with the DNS update.

There are no guarantees here so you will have to make your own decision about the risk of losing data if it fails