问:
tqdm stops showing progress in terminal "... (more hidden) ..."
I am training a neural network and I found it useful to have a tqdm bar showing how many steps in epoch has come.

I faced the following problem:

after reaching the end of a terminal window, it shows ... (more hidden) ... and I cannot do anything about it. I tried scrolling up
  and down in tmux, but it does nothing.

The connection to the Linux server is established through ssh and tmux is used inside the dedicated machine. The code for tqdm is:

```<code>pbar = tqdm(total=4500)
pbar.set_description(f'EPOCH: {epoch}')
pbar.n = *value*
pbar.update()
</code>```

how it looks:
screenshot

Interestingly, tho, that I couldn't find anything connected to "... (more hidden) ..." anywhere in Google.

答:
This happens when there are more nested bars than lines in the terminal.

It can also happen if you forget to close() finished progress bars. Using with will make sure that the bars are closed eventually:

with tqdm(...) as pbar:
   ...
```

Body:
I am training a neural network and I found it useful to have a tqdm bar showing how many steps in epoch has come.

I faced the following problem:

after reaching the end of a terminal window, it shows ... (more hidden) ... and I cannot do anything about it. I tried scrolling up
  and down in tmux, but it does nothing.

The connection to the Linux server is established through ssh and tmux is used inside the dedicated machine. The code for tqdm is:

pbar = tqdm(total=4500)
pbar.set_description(f'EPOCH: {epoch}')
pbar.n = *value*
pbar.update()

how it looks:
screenshot

Interestingly, tho, that I couldn't find anything connected to "... (more hidden) ..." anywhere in Google.


来源: stackexchange

问:
how to access json via jquery
i have this json in my request

```<code>    $.get("/shop_possystems/index.php?route=module/cart/ajax_get_individual_prices&current_id=" + current_id + "&standard_id=" + standard + "&professional_id=" + professional + "&premium_id=" + premium + "&quantity=" + quantity,
        function(data) {
            var standard_price     = data.standard_price;
            var professional_price = data.professional_price;
            var premium_price      = data.premium_price;
                        console.log(data);
                    $prettyCheckBox0.text(standard_price);
                    $prettyCheckBox1.text(professional_price);
                    $prettyCheckBox2.text(premium_price);
    });
</code>```

the problem is that the data.standard_price returns undefined but in the console.log i have this

```<code> "{"standard_price":"included","professional_price":"add $792.00","premium_price":"add $3372.00"}"
</code>```

whats the deal

答:
You need to parse the JSON. Put this as the first line of the callback:

```<code>data = $.parseJSON(data);
</code>```

Alternatively, use $.getJSON instead of $.get or pass "json" as another parameter to $.get.

ContentLicense: CC BY-SA 3.0

Title: how to access json via jquery

Body:
i have this json in my request

    $.get("/shop_possystems/index.php?route=module/cart/ajax_get_individual_prices&current_id=" + current_id + "&standard_id=" + standard + "&professional_id=" + professional + "&premium_id=" + premium + "&quantity=" + quantity,
        function(data) {
            var standard_price     = data.standard_price;
            var professional_price = data.professional_price;
            var premium_price      = data.premium_price;
                        console.log(data);
                    $prettyCheckBox0.text(standard_price);
                    $prettyCheckBox1.text(professional_price);
                    $prettyCheckBox2.text(premium_price);
    });

the problem is that the data.standard_price returns undefined but in the console.log i have this

 "{"standard_price":"included","professional_price":"add $792.00","premium_price":"add $3372.00"}"

whats the deal

Body:
You need to parse the JSON. Put this as the first line of the callback:

data = $.parseJSON(data);

Alternatively, use $.getJSON instead of $.get or pass "json" as another parameter to $.get.


问:
How to set the Value variable of this custom Odin Inspector class
I know, the title is bad, but I couldn't think if a better one. The question is very specific.

Ok, so I'm using a class in my game identical to Odin Inspector's example RPG Skills classes. But it's set up in a way I don't quite understand and I can't work out how to set the value (I can get it, and there is a setter, so it's possible to set too). Also, all the skill classes/structs/etc are in the same .cs file.

The SkillList function I use to get the Value:
(I get it with skills[Strength].Value; in other classes)

```<code>public int this[SkillType type]
{
    get
    {
        for (int i = 0; i < this.skills.Count; i++)
        {
            if (this.skills[i].Type == type)
                return this.skills[i].Value;
        }
        return 0;
    }
    set
    {
        for (int i = 0; i < this.skills.Count; i++)
        {
            if (this.skills[i].Type == type)
            {
                var val = this.skills[i];
                val.Value = value;
                this.skills[i] = val;
                return;
            }
        }
        this.skills.Add(new SkillValue(type, value));
    }
}
</code>```

SkillValue struct:

```<code>[Serializable]
public struct SkillValue : IEquatable<SkillValue>
{
    public SkillType Type;
    public int Value;

    public SkillValue(SkillType type, int value)
    {
        this.Type = type;
        this.Value = value;
    }

    public SkillValue(SkillType type)
    {
        this.Type = type;
        this.Value = 0;
    }

    public bool Equals(SkillValue other)
    { return this.Type == other.Type && this.Value == other.Value; }
}
</code>```

SkillType enum:

```<code>public enum SkillType
{
    Science,
    Technology,
    Arts,
    Language,
}
</code>```

I've tried:

skills[Science].Value = 10;

skills[Science] = new SkillValue(Science, 10);

skills[Science, 10]; (using a new function made by me)

skills[Science](10);

skills[Science].Value(10);

skills[Science] = 10;

But none work, and I'm just guessing randomly now.
How can I set the value?
Thanks

The solution:
character.skills[Rorschach.Character.Skills.SkillType.Science] = value;

答:
Your property is of type int and expects a key of type SkillType so it should probably be

```<code>SkillList skills;

skills[SkillType.Science] = 10;
</code>```

actually also

I get it with skills[Strength].Value;

seems odd with the code you provided. As said the property returns an int which has no property Value so it should actually be

```<code>int x = skills[SkillType.Strength];
</code>```

Now knowing the full implementation code and your actual usage:

```<code>public SkillList skills;
</code>```

...

```<code>public int Science
{
    get { return this.Character.skills[Science].Value; }
    set { this.Character.skills[Science].Value(10); }
}
</code>```

ATTENTION!

What you did here by accident is using the other property

```<code>public SkillValue this[int index]
{
    get { return this.skills[index]; }
    set { this.skills[index] = value; }
}
</code>```

which takes an int index and returns a SkillValue.

BUT you are causing a runtime StackOverlowExeption due to a recursive call of Science.

You can't use Science inside of the getter or setter of equally called property!

Imagine using the getter as example:

You would call

```<code>var test = Science;
</code>```

so it executes the getter

```<code>return Character.skills[Science].Value;
</code>```

but well ... in order to know the value of Science in order to use it here as the index it would again have to execute the getter so again

```<code>return Character.skills[Science].Value;
</code>```

and by now you hopefully get what I mean.

Solution

You property should actually as guessed before rather look like

```<code>public int Science
{
    get { return Character.skills[SkillType.Science]; }
    set { Character.skills[SkillType.Science] = value; }
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I know, the title is bad, but I couldn't think if a better one. The question is very specific.

Ok, so I'm using a class in my game identical to Odin Inspector's example RPG Skills classes. But it's set up in a way I don't quite understand and I can't work out how to set the value (I can get it, and there is a setter, so it's possible to set too). Also, all the skill classes/structs/etc are in the same .cs file.

The SkillList function I use to get the Value:
(I get it with skills[Strength].Value; in other classes)

public int this[SkillType type]
{
    get
    {
        for (int i = 0; i < this.skills.Count; i++)
        {
            if (this.skills[i].Type == type)
                return this.skills[i].Value;
        }
        return 0;
    }
    set
    {
        for (int i = 0; i < this.skills.Count; i++)
        {
            if (this.skills[i].Type == type)
            {
                var val = this.skills[i];
                val.Value = value;
                this.skills[i] = val;
                return;
            }
        }
        this.skills.Add(new SkillValue(type, value));
    }
}

SkillValue struct:

[Serializable]
public struct SkillValue : IEquatable<SkillValue>
{
    public SkillType Type;
    public int Value;

    public SkillValue(SkillType type, int value)
    {
        this.Type = type;
        this.Value = value;
    }

    public SkillValue(SkillType type)
    {
        this.Type = type;
        this.Value = 0;
    }

    public bool Equals(SkillValue other)
    { return this.Type == other.Type && this.Value == other.Value; }
}

SkillType enum:

public enum SkillType
{
    Science,
    Technology,
    Arts,
    Language,
}

I've tried:

skills[Science].Value = 10;

skills[Science] = new SkillValue(Science, 10);

skills[Science, 10]; (using a new function made by me)

skills[Science](10);

skills[Science].Value(10);

skills[Science] = 10;

But none work, and I'm just guessing randomly now.
How can I set the value?
Thanks

The solution:
character.skills[Rorschach.Character.Skills.SkillType.Science] = value;

Body:
Your property is of type int and expects a key of type SkillType so it should probably be

SkillList skills;

skills[SkillType.Science] = 10;

actually also

I get it with skills[Strength].Value;

seems odd with the code you provided. As said the property returns an int which has no property Value so it should actually be

int x = skills[SkillType.Strength];

Now knowing the full implementation code and your actual usage:

public SkillList skills;

...

public int Science
{
    get { return this.Character.skills[Science].Value; }
    set { this.Character.skills[Science].Value(10); }
}

ATTENTION!

What you did here by accident is using the other property

public SkillValue this[int index]
{
    get { return this.skills[index]; }
    set { this.skills[index] = value; }
}

which takes an int index and returns a SkillValue.

BUT you are causing a runtime StackOverlowExeption due to a recursive call of Science.

You can't use Science inside of the getter or setter of equally called property!

Imagine using the getter as example:

You would call

var test = Science;

so it executes the getter

return Character.skills[Science].Value;

but well ... in order to know the value of Science in order to use it here as the index it would again have to execute the getter so again

return Character.skills[Science].Value;

and by now you hopefully get what I mean.

Solution

You property should actually as guessed before rather look like

public int Science
{
    get { return Character.skills[SkillType.Science]; }
    set { Character.skills[SkillType.Science] = value; }
}


问:
ActiveSheets.Copy generates Path/File Acces Error (Error 75)
I would like to copy the active Excel sheet (the one the  user has currently manually selected) and save it as a workbook to a specified folder.

I am using code that I know works (it is copied from another user). Whenever the code hits the ActiveSheet.Copy line, it stops and shows a Path/File access error (Error 75).

If I remove the ActiveSheet.Copy line of code, the code works fine but it  saves the entire workbook to the folder instead of the active sheet. I noticed  that if  I try to  manually copy a sheet to a new Workbook in Excel, this works fine for a .xlsx workbook but if the workbook is .xlsm, the manual process does not work.

To be clear, the manual process is:

right click on a tab/worksheet

select Move or Copy from the menu

tick the "Create a copy" box

select "new book" from the drop down menu

This should create a new workbook with the  sheet you had  selected.  The same person that gave me the  code that works on their machine is able to copy a worksheet manually to a new workbook even from a workbook with a .xlsm extension.

I have a brand new ThinkPad and I have not changed any default  settings. I have looked online for help with this issue but can't find any relevant answers. It does  seem to be a settings issue  of  some sort because the code and  the  manual process works on my friends computer but does not  on mine.

May 30th Update:
Thank you for the responses and for the  formatting help. I have tried to observe the formatting conventions in this new update.

When the code reaches  the  ActiveSheet.Copy line and stops, the following is the  sequence of events:

Path/File Access Error

Hit "Help" - it displays Path/File access error 75 and takes me to Microsoft's URL - I found nothing of help on the Error 75 help page

Run Time Error '1004' "We couldn't copy this sheet" is displayed.

When I hit the debug button on the  run time error, it just highlights in yellow the ActiveSheet.Copyline of code. No more messages are displayed.

Please note: I was running the code on One Drive in a Workbook.xlsm and trying to save to the local drive on my computer. When I removed the ActiveSheet.Copyline of code, I  was able to save the  entire workbook.xlsm to the appropriate folder so that makes me think it is not a path issues.

However, when I moved the workbook.xlsm with the code to the local drive, I was able to run the macro successfully with the ActiveSheet.Copyline of code. This happened yesterday after I posted my original question.
I found that  when I manually  clicked  on a tab(sheet) to copy and save it to a new workbook, that also worked for the workbook.xlsm as long as it was on the local drive.

I was be able to save the entire workbook.xlsm (not a sheet) to my local C: drive from the One Drive when I removed the ActiveSheet.Copyline of code.  This makes me think it is not a path issue because I am able to save to the folder I specify, I just can't copy and save a  sheet.   I do not consider the case closed and am still struggling to understand 1) Why I can't run the code with the ActiveSheet.Copyline of code from the One Drive; 2) why the manual process of copying a sheet to a new workbook does not work on One Drive in xlsm but does on the local drive.

Here is  the code:

```<code>  Sub SaveMe()

'Application.ScreenUpdating = False

Dim MyTm As String          'Holds the Territory Manager "Code"
Dim MySavePath As Variant   'Holds the path to save the file
Dim MyFileName As String    'Holds the file name
Dim MyYear As Integer       'Holds the year
Dim MyMonth As Integer      'Holds the month
Dim MyDay As Integer        'Holds the day

MyYear = Year(Now)
MyMonth = Month(Now)
MyDay = Day(Now)

MyTm = Left(ActiveSheet.Name, 4)
MySavePath = Application.WorksheetFunction.VLookup(MyTm, Range("TMSavePath"), 2, False)

    ActiveSheet.Copy

    ActiveWorkbook.SaveAs Filename:= _
        MySavePath & "\" & MyYear & MyMonth & MyDay & " - " & ActiveSheet.Name & ".xlsx", FileFormat:= _
        xlOpenXMLWorkbook, CreateBackup:=False
    ActiveWindow.Close

'Application.ScreenUpdating = True

End Sub
</code>```

Thank you!

答:
Try this code:</p>

```<code>Sub moveActvieSheetToAnotherWB()

Application.DisplayAlerts = False

Dim wb As String
Dim sht As String
Dim newWb As Workbook

wb = ActiveWorkbook.Name
sht = ActiveSheet.Name
'

Set newWb = Workbooks.Add
Workbooks(wb).Sheets(sht).Copy before:=newWb.Sheets(1)

'disable popup before delete empty tab
Application.DisplayAlerts = False
newWb.Sheets(2).Delete

'full path
'newWb.SaveAs "newFilename.xlsx"
End Sub
</code>```

Body:
I would like to copy the active Excel sheet (the one the  user has currently manually selected) and save it as a workbook to a specified folder.

I am using code that I know works (it is copied from another user). Whenever the code hits the ActiveSheet.Copy line, it stops and shows a Path/File access error (Error 75).

If I remove the ActiveSheet.Copy line of code, the code works fine but it  saves the entire workbook to the folder instead of the active sheet. I noticed  that if  I try to  manually copy a sheet to a new Workbook in Excel, this works fine for a .xlsx workbook but if the workbook is .xlsm, the manual process does not work.

To be clear, the manual process is:

right click on a tab/worksheet

select Move or Copy from the menu

tick the "Create a copy" box

select "new book" from the drop down menu

This should create a new workbook with the  sheet you had  selected.  The same person that gave me the  code that works on their machine is able to copy a worksheet manually to a new workbook even from a workbook with a .xlsm extension.

I have a brand new ThinkPad and I have not changed any default  settings. I have looked online for help with this issue but can't find any relevant answers. It does  seem to be a settings issue  of  some sort because the code and  the  manual process works on my friends computer but does not  on mine.

May 30th Update:
Thank you for the responses and for the  formatting help. I have tried to observe the formatting conventions in this new update.

When the code reaches  the  ActiveSheet.Copy line and stops, the following is the  sequence of events:

Path/File Access Error

Hit "Help" - it displays Path/File access error 75 and takes me to Microsoft's URL - I found nothing of help on the Error 75 help page

Run Time Error '1004' "We couldn't copy this sheet" is displayed.

When I hit the debug button on the  run time error, it just highlights in yellow the ActiveSheet.Copyline of code. No more messages are displayed.

Please note: I was running the code on One Drive in a Workbook.xlsm and trying to save to the local drive on my computer. When I removed the ActiveSheet.Copyline of code, I  was able to save the  entire workbook.xlsm to the appropriate folder so that makes me think it is not a path issues.

However, when I moved the workbook.xlsm with the code to the local drive, I was able to run the macro successfully with the ActiveSheet.Copyline of code. This happened yesterday after I posted my original question.
I found that  when I manually  clicked  on a tab(sheet) to copy and save it to a new workbook, that also worked for the workbook.xlsm as long as it was on the local drive.

I was be able to save the entire workbook.xlsm (not a sheet) to my local C: drive from the One Drive when I removed the ActiveSheet.Copyline of code.  This makes me think it is not a path issue because I am able to save to the folder I specify, I just can't copy and save a  sheet.   I do not consider the case closed and am still struggling to understand 1) Why I can't run the code with the ActiveSheet.Copyline of code from the One Drive; 2) why the manual process of copying a sheet to a new workbook does not work on One Drive in xlsm but does on the local drive.

Here is  the code:

  Sub SaveMe()

'Application.ScreenUpdating = False

Dim MyTm As String          'Holds the Territory Manager "Code"
Dim MySavePath As Variant   'Holds the path to save the file
Dim MyFileName As String    'Holds the file name
Dim MyYear As Integer       'Holds the year
Dim MyMonth As Integer      'Holds the month
Dim MyDay As Integer        'Holds the day

MyYear = Year(Now)
MyMonth = Month(Now)
MyDay = Day(Now)

MyTm = Left(ActiveSheet.Name, 4)
MySavePath = Application.WorksheetFunction.VLookup(MyTm, Range("TMSavePath"), 2, False)

    ActiveSheet.Copy

    ActiveWorkbook.SaveAs Filename:= _
        MySavePath & "\" & MyYear & MyMonth & MyDay & " - " & ActiveSheet.Name & ".xlsx", FileFormat:= _
        xlOpenXMLWorkbook, CreateBackup:=False
    ActiveWindow.Close

'Application.ScreenUpdating = True

End Sub

Thank you!

Body:
Try this code:

Sub moveActvieSheetToAnotherWB()

Application.DisplayAlerts = False

Dim wb As String
Dim sht As String
Dim newWb As Workbook

wb = ActiveWorkbook.Name
sht = ActiveSheet.Name
'

Set newWb = Workbooks.Add
Workbooks(wb).Sheets(sht).Copy before:=newWb.Sheets(1)

'disable popup before delete empty tab
Application.DisplayAlerts = False
newWb.Sheets(2).Delete

'full path
'newWb.SaveAs "newFilename.xlsx"
End Sub


问:
DB2 keeps returning "duplicate name" when trying to add a non-existent column via Flyway with Spring Boot
How do I add columns to DB2 tables via Flyway? I have 2 flyway migration scripts. V1 is the initial creation of the database. V2 is trying to add a column to different tables that has been left out of V1.

```<code>ALTER TABLE TABLE1
ADD CODE VARCHAR(20);

ALTER TABLE TABLE2
ADD CODE VARCHAR(20);

ALTER TABLE TABLE3
ADD CODE VARCHAR(20);
</code>```

This certainly seems simple enough. However, flyway gets a response of DB2 SQL Error: SQLCODE=-612, SQLSTATE=42711, SQLERRMC=CODE which is the error for duplicate columns when trying to add more than 1 line of these at a time. So adding a column to TABLE1 works, same for TABLE2. But, if execute both I get the error.

How should I be structuring these queries so that they don't conflict?

答:
Despite the DB2 error this is not a DB2 problem, but a Flyway one. You cannot add the same column to multiple tables with consecutive queries. There must be a query in between OR the queries must be in different migration files.

This works.

```<code>ALTER TABLE TABLE1 ADD CODE VARCHAR(20);
CREATE INDEX index1 ON TABLE1(CODE);

ALTER TABLE TABLE2 ADD CODE VARCHAR(20);
CREATE INDEX index2 ON TABLE2(CODE);

ALTER TABLE TABLE3 ADD CODE VARCHAR(20);
CREATE INDEX index2 ON TABLE3(CODE);
</code>```

Body:
How do I add columns to DB2 tables via Flyway? I have 2 flyway migration scripts. V1 is the initial creation of the database. V2 is trying to add a column to different tables that has been left out of V1.

ALTER TABLE TABLE1
ADD CODE VARCHAR(20);

ALTER TABLE TABLE2
ADD CODE VARCHAR(20);

ALTER TABLE TABLE3
ADD CODE VARCHAR(20);

This certainly seems simple enough. However, flyway gets a response of DB2 SQL Error: SQLCODE=-612, SQLSTATE=42711, SQLERRMC=CODE which is the error for duplicate columns when trying to add more than 1 line of these at a time. So adding a column to TABLE1 works, same for TABLE2. But, if execute both I get the error.

How should I be structuring these queries so that they don't conflict?

Body:
Despite the DB2 error this is not a DB2 problem, but a Flyway one. You cannot add the same column to multiple tables with consecutive queries. There must be a query in between OR the queries must be in different migration files.

This works.

ALTER TABLE TABLE1 ADD CODE VARCHAR(20);
CREATE INDEX index1 ON TABLE1(CODE);

ALTER TABLE TABLE2 ADD CODE VARCHAR(20);
CREATE INDEX index2 ON TABLE2(CODE);

ALTER TABLE TABLE3 ADD CODE VARCHAR(20);
CREATE INDEX index2 ON TABLE3(CODE);


问:
SQL query not executing as whole
So I have a query that should add Primary Key to the Id field:

```<code>IF NOT EXISTS(SELECT *
              FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
              WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = 'CAL')
BEGIN
    DROP INDEX IF EXISTS CAL$01 ON dbo.CAL;

    ALTER TABLE BTS.dbo.CAL
    ALTER COLUMN Intern INT NOT NULL;

    ALTER TABLE BTS.dbo.CAL
        ADD CONSTRAINT PK_CAL_Intern PRIMARY KEY (Intern);

    CREATE INDEX CAL$01
    ON CAL (Intern);
END
</code>```

The problem is that when I chose all this code and execute (F5), I get this error:

Whereas when I'm choosing every statement one by one it works as expected:

I am sure that the IF works as expected

I tried to use GO between statements, it's not allowed.

I should execute this code on a large number of tables

Maybe I don't know something about how SQL Server Management Studio executes statements

答:
Before a query is run it is parsed. This is why what you're doing is failing. SQL server is checking the details of the Intern before the script is run. At the point you start to try to run the script, Intern in the table BTS.dbo.CAL is NULLable, and so the script fails.

You can get around this by running the statement to create the primary key cosntraint in a separate scope:

```<code>IF NOT EXISTS(
    SELECT *
    FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
    WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = 'CAL'
)
BEGIN
    DROP INDEX IF EXISTS CAL$01 ON dbo.CAL;

    ALTER TABLE
      BTS.dbo.CAL
    ALTER COLUMN
      Intern
        INT NOT NULL;

    EXEC sys.sp_executesql N'ALTER TABLE BTS.dbo.CAL ADD CONSTRAINT PK_CAL_Intern PRIMARY KEY (Intern);';

    CREATE INDEX [CAL$01]
    ON CAL (Intern);
END'
</code>```

Title: SQL query not executing as whole

Body:
So I have a query that should add Primary Key to the Id field:

IF NOT EXISTS(SELECT *
              FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
              WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = 'CAL')
BEGIN
    DROP INDEX IF EXISTS CAL$01 ON dbo.CAL;

    ALTER TABLE BTS.dbo.CAL
    ALTER COLUMN Intern INT NOT NULL;

    ALTER TABLE BTS.dbo.CAL
        ADD CONSTRAINT PK_CAL_Intern PRIMARY KEY (Intern);

    CREATE INDEX CAL$01
    ON CAL (Intern);
END

The problem is that when I chose all this code and execute (F5), I get this error:

Whereas when I'm choosing every statement one by one it works as expected:

I am sure that the IF works as expected

I tried to use GO between statements, it's not allowed.

I should execute this code on a large number of tables

Maybe I don't know something about how SQL Server Management Studio executes statements

Body:
Before a query is run it is parsed. This is why what you're doing is failing. SQL server is checking the details of the Intern before the script is run. At the point you start to try to run the script, Intern in the table BTS.dbo.CAL is NULLable, and so the script fails.

You can get around this by running the statement to create the primary key cosntraint in a separate scope:

IF NOT EXISTS(
    SELECT *
    FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS
    WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = 'CAL'
)
BEGIN
    DROP INDEX IF EXISTS CAL$01 ON dbo.CAL;

    ALTER TABLE
      BTS.dbo.CAL
    ALTER COLUMN
      Intern
        INT NOT NULL;

    EXEC sys.sp_executesql N'ALTER TABLE BTS.dbo.CAL ADD CONSTRAINT PK_CAL_Intern PRIMARY KEY (Intern);';

    CREATE INDEX [CAL$01]
    ON CAL (Intern);
END'


问:
Storing Application Default Credentials securely in KMS
We have a Java app which uses Google Auth to allow uses in. The app needs to connect to a Google Cloud SQL database which is locked down behind IP restrictions.

We need to use Cloud SQL Socket Factory with Cloud SQL Proxy to get access to the database, this requires Application Default Credentials with an environment variable GOOGLE_APPLICATION_CREDENTIALS pointing at service account credentials JSON file. I'm unsure of how to store this securely, putting that file on the user's PC is obviously not secure.

As per best practices on https://cloud.google.com/docs/authentication/production, it says

You can use an environment variable pointing to credentials outside of the application's source code, such as Cloud Key Management Service.

But this doesn't go on to explain how to do it. How can I store this file securely, in KMS or otherwise, in a way that only authorized Google accounts can access?

答:
You are right: using service account key file isn't a good practice and it's a security breach (in addition of storing it securely on computer, you have to rotate it every 90 days, you can copy the file, send it by email and even commit it publicly on git repo!!)

However, for using cloud SQL proxy, you can simply use your own credential. perform a gcloud auth application-default login. By sure that your user is authorized on the database and that's all!

Note: be sure to not use the param -credential when you start your cloud sql proxy


问:
how to use CMake file (GLOB SRCS *. ) with a build directory
this is my current CMakeLists.txt file

```<code>cmake_minimum_required(VERSION 3.3)
set(CMAKE_C_FLAGS " -Wall -g ")
project( bmi )
file( GLOB SRCS *.cpp *.h )
add_executable( bmi ${SRCS})
</code>```

This builds from my source directory, but I have to clean up all the extra files   after. My question is how do I build this from a build directory if all my source files are in the same source directory?

thanks

答:
Cmake used to only update the list of source files if CMakeLists.txt was changed since the last cmake run or if cmake was used to configure the project again.

In cmake 3.11.0 recursive search and automatic re-configuration on adding or deleting source files was added. Since then you can use the following snippet:

```<code>if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.11.0")
    file(GLOB_RECURSE SOURCE_FILES CONFIGURE_DEPENDS *.cpp *.h)
else()
    file(GLOB SOURCE_FILES *.cpp *.h */*.h */*.cpp)
endif()
</code>```

The file() command after the else() provides at least a bit of backwards compatibility: It still searches for source files in the current folder and its direct subfolders. But it doesn't automatically recognize if there are new files or old files have been deleted.

Note that VERSION_GREATER_EQUAL is only available in cmake >= 3.7

Body:
this is my current CMakeLists.txt file

cmake_minimum_required(VERSION 3.3)
set(CMAKE_C_FLAGS " -Wall -g ")
project( bmi )
file( GLOB SRCS *.cpp *.h )
add_executable( bmi ${SRCS})

This builds from my source directory, but I have to clean up all the extra files   after. My question is how do I build this from a build directory if all my source files are in the same source directory?

thanks

Body:
Cmake used to only update the list of source files if CMakeLists.txt was changed since the last cmake run or if cmake was used to configure the project again.

In cmake 3.11.0 recursive search and automatic re-configuration on adding or deleting source files was added. Since then you can use the following snippet:

if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.11.0")
    file(GLOB_RECURSE SOURCE_FILES CONFIGURE_DEPENDS *.cpp *.h)
else()
    file(GLOB SOURCE_FILES *.cpp *.h */*.h */*.cpp)
endif()

The file() command after the else() provides at least a bit of backwards compatibility: It still searches for source files in the current folder and its direct subfolders. But it doesn't automatically recognize if there are new files or old files have been deleted.

Note that VERSION_GREATER_EQUAL is only available in cmake >= 3.7


问:
Refresh datalist in view after user finishes typing in textbox Angular 7
I am trying to refresh a datalist in the view after waiting for user to finish typing in the textbox and updating results. Tried with angular directives, tried with Observable and various timeouts and debounces and no luck. I ran out of options.

In the html file:

```<code>            <input type="text" class="form-control" id="Other"
            (keyup)="onKeySearch($event)" list="dynamicList" formControlName="Other"/>

            <datalist id="dynamicList">
                <option *ngFor="let employee of employeesList" [value]="employee.Name">
                    {{employee.Name}}</option>
            </datalist>
</code>```

in the .ts file:

```<code>  public employeesList: EmployeeData[] = [];

  timeout: any = null;

  getEmployeesList(name : string) {
      let empList: EmployeeData[] = [];

      // get employees list from service
      this.employeeService.getEmployeesList(name).subscribe((data: any) => {
        empList = data;
        console.log(empList)
      })
      return empList;
    }

  public onKeySearch(event: any) {
    let empListt: EmployeeData[] = [];

    clearTimeout(this.timeout);
    var $this = this;
    this.timeout = setTimeout(() => {
        empListt = $this.getEmployeesList(event.target.value);
        console.log(empListt)
    }, 1000);
    this.employeesList = empListt;
  }
</code>```

The problem is that the datalist is not updates after retrieving the data an populating the list. After it exists the method the list is again empty, thus no data to display.

I have added stackblitz example code with similar code as above (same behavior):

.ts file:

```<code>import { Component, VERSION, OnInit } from "@angular/core";
import { FormControl } from "@angular/forms";
import { distinctUntilChanged, debounceTime, tap } from "rxjs/operators";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  searchControl = new FormControl("");
  message = "";
  public employeesList: string[] = [];

  ngOnInit() {
    this.searchControl.valueChanges
      .pipe(
        tap(() => (this.message = "User is typing...")),
        distinctUntilChanged(),
        debounceTime(1000)
      )
      .subscribe(res => {
        this.message = "User finished typing!";
        this.employeesList.push('1');
        this.employeesList.push('2');
        this.employeesList.push('3');
      });
  }
}
</code>```

.html file:

```<code><input [formControl]="searchControl" list="dynamicList">

<datalist id="dynamicList">
    <option *ngFor="let employee of employeesList">
        {{employee}}</option>
</datalist>

<span> {{message}} </span>
</code>```

答:
The dropdown will be filtered according to the text you have entered. So, in the given example, since you have pushed 1,2 and 3 values into the list, the drop down will only list with the filtered value.

Eg. if you input 1, the drop down list will have 1 (which is the required functionality)

You can see this behavior clearly if you slightly change the test input as :

```<code>  ngOnInit() {
    this.searchControl.valueChanges
      .pipe(
        tap(() => (this.message = "User is typing...")),
        distinctUntilChanged(),
        debounceTime(1000)
      )
      .subscribe(res => {
        this.message = "User finished typing!";
        this.employeesList.push('Employee 1');
        this.employeesList.push('Employee 2');
        this.employeesList.push('Employee 3');
      });
  }
</code>```

Now, when you search 'Employee', it will list all 3, and if you search 'Employee 1', it will list the required one entry only. (Which is the expected behavior)

Body:
I am trying to refresh a datalist in the view after waiting for user to finish typing in the textbox and updating results. Tried with angular directives, tried with Observable and various timeouts and debounces and no luck. I ran out of options.

In the html file:

            <input type="text" class="form-control" id="Other"
            (keyup)="onKeySearch($event)" list="dynamicList" formControlName="Other"/>

            <datalist id="dynamicList">
                <option *ngFor="let employee of employeesList" [value]="employee.Name">
                    {{employee.Name}}</option>
            </datalist>

in the .ts file:

  public employeesList: EmployeeData[] = [];

  timeout: any = null;

  getEmployeesList(name : string) {
      let empList: EmployeeData[] = [];

      // get employees list from service
      this.employeeService.getEmployeesList(name).subscribe((data: any) => {
        empList = data;
        console.log(empList)
      })
      return empList;
    }

  public onKeySearch(event: any) {
    let empListt: EmployeeData[] = [];

    clearTimeout(this.timeout);
    var $this = this;
    this.timeout = setTimeout(() => {
        empListt = $this.getEmployeesList(event.target.value);
        console.log(empListt)
    }, 1000);
    this.employeesList = empListt;
  }

The problem is that the datalist is not updates after retrieving the data an populating the list. After it exists the method the list is again empty, thus no data to display.

I have added stackblitz example code with similar code as above (same behavior):

.ts file:

import { Component, VERSION, OnInit } from "@angular/core";
import { FormControl } from "@angular/forms";
import { distinctUntilChanged, debounceTime, tap } from "rxjs/operators";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  searchControl = new FormControl("");
  message = "";
  public employeesList: string[] = [];

  ngOnInit() {
    this.searchControl.valueChanges
      .pipe(
        tap(() => (this.message = "User is typing...")),
        distinctUntilChanged(),
        debounceTime(1000)
      )
      .subscribe(res => {
        this.message = "User finished typing!";
        this.employeesList.push('1');
        this.employeesList.push('2');
        this.employeesList.push('3');
      });
  }
}

.html file:

<input [formControl]="searchControl" list="dynamicList">

<datalist id="dynamicList">
    <option *ngFor="let employee of employeesList">
        {{employee}}</option>
</datalist>

 {{message}}

Body:
The dropdown will be filtered according to the text you have entered. So, in the given example, since you have pushed 1,2 and 3 values into the list, the drop down will only list with the filtered value.

Eg. if you input 1, the drop down list will have 1 (which is the required functionality)

You can see this behavior clearly if you slightly change the test input as :

  ngOnInit() {
    this.searchControl.valueChanges
      .pipe(
        tap(() => (this.message = "User is typing...")),
        distinctUntilChanged(),
        debounceTime(1000)
      )
      .subscribe(res => {
        this.message = "User finished typing!";
        this.employeesList.push('Employee 1');
        this.employeesList.push('Employee 2');
        this.employeesList.push('Employee 3');
      });
  }

Now, when you search 'Employee', it will list all 3, and if you search 'Employee 1', it will list the required one entry only. (Which is the expected behavior)


问:
Could not validate provider configuration: 2 errors occurred - Invalid or Unknown Key Pulumi
I'm currently using Pulumi TypeScript's Infrastructure as Code and I've been enjoying it so far. Unfortunately, I've hit a major roadblock. I was trying to create a SSM Parameter's store in my Pulumi config:

const config = new pulumi.Config();
const auth0ClientSecret = config.requireSecret("auth0-client_secret");
const auth0ClientId = config.requireSecret("auth0-client_id");

const auth0ClientSecretSSM = new aws.ssm.Parameter(
  "auth0-client_secret",
  {
    name: "auth0_client_secret_" + env,
    type: "SecureString",
    value: auth0ClientSecret,
  }
);

const auth0ClientIdSecretSSM = new aws.ssm.Parameter("auth0-client_id", {
  type: "SecureString",
  value: auth0ClientId,
});
```

<p>I tried doing this. I set up the secrets to the config accordingly:</p>

<p><code>pulumi config set --secret auth0-client_secret thesecret</code>
<code>pulumi config set --secret auth0-client_id theId</code></p>

<p>After that, and running <code>pulumi up</code>, I got hit with:</p>

<pre class="lang-yaml prettyprint-override"><code>Diagnostics:
  aws:iam:Policy (schon-SQS-send-messages-dev):
    error: could not validate provider configuration: 2 errors occurred:
        * : invalid or unknown key: auth0_client_id
        * : invalid or unknown key: auth0_client_secret
</code>```

And I haven't been able to get rid of that error ever since! I've been hitting my head for over 40 minutes by turning off/on pieces of code, and the only thing that it seems to work is if I start in blank state, in which Pulumi asks to delete all of my resources (something, of course, that I don't want to do).

I've tried:
-  pulumi config rm auth0_client_secret
-  pulumi config rm auth0-client_secret

I went into the User:/.pulumi folder in my Windows machine to see where could it be lying. No answer.

It seems that the problem lies in how Pulumi tends to see the hyphen - .

Is there a way to reset Pulumi's config? I even tried looking at the Yaml files and re-creating the keys and deleting them again to no avail. I can't seem to find anything online either.

Just this:
https://www.pulumi.com/docs/intro/concepts/config/#changing-the-secrets-provider-for-a-stack

Any ideas?

Thank you!!

答:
I ended up posting the issue on GitHub as well. Thanks to the promptly reply from the team, it was pointed out that I was using aws as the project name, and that created a namespace problem. Renaming my stack to something else made everything work as expected.

I did

pulumi stack rename /my_user/new_project_name/dev

pulumi stack rename /my_user/new_project_name/prod

Body:
I'm currently using Pulumi TypeScript's Infrastructure as Code and I've been enjoying it so far. Unfortunately, I've hit a major roadblock. I was trying to create a SSM Parameter's store in my Pulumi config:

const config = new pulumi.Config();
const auth0ClientSecret = config.requireSecret("auth0-client_secret");
const auth0ClientId = config.requireSecret("auth0-client_id");

const auth0ClientSecretSSM = new aws.ssm.Parameter(
  "auth0-client_secret",
  {
    name: "auth0_client_secret_" + env,
    type: "SecureString",
    value: auth0ClientSecret,
  }
);

const auth0ClientIdSecretSSM = new aws.ssm.Parameter("auth0-client_id", {
  type: "SecureString",
  value: auth0ClientId,
});

I tried doing this. I set up the secrets to the config accordingly:

pulumi config set --secret auth0-client_secret thesecret
pulumi config set --secret auth0-client_id theId

After that, and running pulumi up, I got hit with:

Diagnostics:
  aws:iam:Policy (schon-SQS-send-messages-dev):
    error: could not validate provider configuration: 2 errors occurred:
        * : invalid or unknown key: auth0_client_id
        * : invalid or unknown key: auth0_client_secret

And I haven't been able to get rid of that error ever since! I've been hitting my head for over 40 minutes by turning off/on pieces of code, and the only thing that it seems to work is if I start in blank state, in which Pulumi asks to delete all of my resources (something, of course, that I don't want to do).

I've tried:
-  pulumi config rm auth0_client_secret
-  pulumi config rm auth0-client_secret

I went into the User:/.pulumi folder in my Windows machine to see where could it be lying. No answer.

It seems that the problem lies in how Pulumi tends to see the hyphen - .

Is there a way to reset Pulumi's config? I even tried looking at the Yaml files and re-creating the keys and deleting them again to no avail. I can't seem to find anything online either.

Just this:
https://www.pulumi.com/docs/intro/concepts/config/#changing-the-secrets-provider-for-a-stack

Any ideas?

Thank you!!


问:
If StartMenuInternet is not set, where else can I look for the default browser?
```<code>key = Registry.CurrentUser.OpenSubKey(@"Software\Clients\StartMenuInternet", false);
if (key == null)
{
    key = Registry.LocalMachine.OpenSubKey(@"Software\Clients\StartMenuInternet", false);
}
</code>```

On a very few machines this is coming up blank.  When regedit is probed, the key is found to be (value not found).  What are my options?

答:
I'm assuming you want to launch a website in the default browser:

```<code>string url = "http://server.com";
Process.Start(url);
</code>```

will do it.

Body:
key = Registry.CurrentUser.OpenSubKey(@"Software\Clients\StartMenuInternet", false);
if (key == null)
{
    key = Registry.LocalMachine.OpenSubKey(@"Software\Clients\StartMenuInternet", false);
}

On a very few machines this is coming up blank.  When regedit is probed, the key is found to be (value not found).  What are my options?

Body:
I'm assuming you want to launch a website in the default browser:

string url = "http://server.com";
Process.Start(url);

will do it.


问:
Public IP of AWS Internet gateway
I would like to know the public IP of AWS internet gateway. My client needs it to do an IP whitelist.
How can I get it? My instance is faced to the internet directly and didn't route via any NAT gateway.
From my understanding, The public IP should be the elastic IP of EC2 instance, which connects to my client. Can any guy make sure of my understanding?

Thanks

答:
You are correct.

An Internet Gateway is a logical connection between a VPC and the Internet. If there is no Internet Gateway, then there is no connection between the VPC and the Internet.

Every Amazon EC2 instance in a VPC has a private IP address. They can optionally also have a public IP address. This can either be a random one assigned when an instance is started, or a static Elastic IP address can be assigned to the instance.

Actually, these public IP addresses are assigned to an Elastic Network Interface (ENI). An instance can have multiple ENIs.

The instance itself doesn't actually 'know' that it has a public IP address / Elastic IP address. Instead, when traffic comes from the Internet destined for the public IP address, the Internet Gateway performs a reverse NAT and sends the traffic to the private IP address of the instance. Similarly, any traffic going from the instance to the Internet Gateway comes from the private IP address of the instance, which the Internet Gateway then forwards as coming from the instance's public IP address.

Thus, the Internet Gateway 'owns' the public IP address, but forwards it to the instance. It's all quite magical, so sometimes it's just easier to imagine as the instance having the public IP address.

One benefit of this method is that an Elastic IP address can be reassigned to another instance and traffic will immediately flow to the new instance without any configuration changes on the 'old' or 'new' instance. They just get traffic via their private IP addresses without knowing that a public IP address was involved.

Title: Public IP of AWS Internet gateway


问:
Swift expression from Result success value falling back to error
How can I get a value that is derived from Result's success value in the case of success or from an error value in the case of failure, without having to create a temporary variable?

Here's a working but verbose example of what I'm trying to do:

let result = Result<Int, Error>.success(1)

let displayText: String
switch result {
case let .success(value): displayText = String(value)
case let .failure(error): displayText = "Result not available. \(error)"
}

updateDisplayText(displayText)
```

<p>I could get something close to what by converting the result to an optional value in the desired format, testing it with try operator, and using the nil-coalescing operator to provide the fallback.</p>

<pre class="lang-swift prettyprint-override"><code>updateDisplayText((try? result.map{ v in String(v) }.get()) ?? "Result not available.")
</code>```

However, that approach doesn't access the failure's error. It also seems overly complex. Is there an approach that works with a single expression, similar to what can be done with an F# match expression?

答:
There are no "match expressions" in Swift. As far as I know, if you want to match against enums with associated values, you must use some kind of statement, whether that's an if case or switch or whatever.

However, no one can stop you from putting that statement into a method, which you can then put inside an extension!

```<code>extension Result {
    func mapBoth<T>(success: (Success) -> T, error: (Failure) -> T) -> T {
        switch self {
        case .success(let s):
            return success(s)
        case .failure(let e):
            return error(e)
        }
    }
}
</code>```

updateDisplayText can then be called like this:

```<code>updateDisplayText(result.mapBoth(
    success: { String($0) },
    failure: { "Result not available. \($0)" }
))
</code>```

Body:
How can I get a value that is derived from Result's success value in the case of success or from an error value in the case of failure, without having to create a temporary variable?

Here's a working but verbose example of what I'm trying to do:

let result = Result<Int, Error>.success(1)

let displayText: String
switch result {
case let .success(value): displayText = String(value)
case let .failure(error): displayText = "Result not available. \(error)"
}

updateDisplayText(displayText)

I could get something close to what by converting the result to an optional value in the desired format, testing it with try operator, and using the nil-coalescing operator to provide the fallback.

updateDisplayText((try? result.map{ v in String(v) }.get()) ?? "Result not available.")

However, that approach doesn't access the failure's error. It also seems overly complex. Is there an approach that works with a single expression, similar to what can be done with an F# match expression?

Body:
There are no "match expressions" in Swift. As far as I know, if you want to match against enums with associated values, you must use some kind of statement, whether that's an if case or switch or whatever.

However, no one can stop you from putting that statement into a method, which you can then put inside an extension!

extension Result {
    func mapBoth<T>(success: (Success) -> T, error: (Failure) -> T) -> T {
        switch self {
        case .success(let s):
            return success(s)
        case .failure(let e):
            return error(e)
        }
    }
}

updateDisplayText can then be called like this:

updateDisplayText(result.mapBoth(
    success: { String($0) },
    failure: { "Result not available. \($0)" }
))


问:
sshfs with different gid on remote
I don't know how to mount a remote directory
"remote_dir" on computer "remote", having remote gid "wgrp".
Help is welcome.

```
  me@local$ sshfs me@remote:/remote_dir remote_as_wgrp ...wanted_options...
```

A workaround is to create a new user "me_wgrp" belonging to group "wgrp".
But the problem seems conceptually so simple that I'm sure there is a solution.

Context:

I'm able to connect using ssh on remote compute, and then to change my gid:

```
  me@local$ ssh me@remote
  me@remote$ newgrp wgrp
```

Now I can create files in directories which are only writable by the group "wgrp".

I have tried

```
  sshfs me@remote:/remote_dir remote_as_wgrp -o ssh_command='newgrp wgrp'
```

but sshfs seems blocked.

Also, if I try

```
  ssh me@remote 'newgrp wgrp'
```

ssh doesn't give the prompt, but it accepts commands.

答:
Ten years after the question was asked, I needed this myself.

I found that it is now possible to add a parameter to sshfs:

```<code>sshfs -o sftp_server="sg <group> -c '/usr/lib/misc/sftp-server -u <umask>'" ...
</code>```

where /usr/lib/misc/sftp-server is the location of sftp-server on the remote system, <group> is the desired group on the remote system, and -u <umask> is an optional way of providing a default umask for the particular sftp-server.

ContentLicense: CC BY-SA 2.5

Title: sshfs with different gid on remote

Body:
I don't know how to mount a remote directory
"remote_dir" on computer "remote", having remote gid "wgrp".
Help is welcome.

  me@local$ sshfs me@remote:/remote_dir remote_as_wgrp ...wanted_options...

A workaround is to create a new user "me_wgrp" belonging to group "wgrp".
But the problem seems conceptually so simple that I'm sure there is a solution.

Context:

I'm able to connect using ssh on remote compute, and then to change my gid:

  me@local$ ssh me@remote
  me@remote$ newgrp wgrp

Now I can create files in directories which are only writable by the group "wgrp".

I have tried

  sshfs me@remote:/remote_dir remote_as_wgrp -o ssh_command='newgrp wgrp'

but sshfs seems blocked.

Also, if I try

  ssh me@remote 'newgrp wgrp'

ssh doesn't give the prompt, but it accepts commands.

Body:
Ten years after the question was asked, I needed this myself.

I found that it is now possible to add a parameter to sshfs:

sshfs -o sftp_server="sg <group> -c '/usr/lib/misc/sftp-server -u <umask>'" ...

where /usr/lib/misc/sftp-server is the location of sftp-server on the remote system, <group> is the desired group on the remote system, and -u <umask> is an optional way of providing a default umask for the particular sftp-server.


问:
How to change the google maps marker color to grey in android
Things I already know

1) Create MarkerOptions object.

2) Use object.icon(BitmapDescriptorFactory.defaultMarker(<color value>));

3) The color value is the hue color value. there are some standard color values specified by Google (HUE.BLUE, HUE.AZURE etc)

4) To get the desired color choose a value between 0 and 360. 0 is red, 90 is cyan, 270 is purple

What do I need?
 This specific float value for grey

My research: Color wheel
Grey is not included in HUE colors. It is in Tone. So how to access color values in Tones.

答:
For those of us who actually want to use the existing hue colors, you can do something like this:</p>

```<code>
fun MapFragment.addGreenMarker(latLng: LatLng) {
    getMap()?.apply {
        addMarker(
            MarkerOptions()
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
                .position(latLng)
                .draggable(true)
        )
    }
}

</code>```

Body:
For those of us who actually want to use the existing hue colors, you can do something like this:

fun MapFragment.addGreenMarker(latLng: LatLng) {
    getMap()?.apply {
        addMarker(
            MarkerOptions()
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
                .position(latLng)
                .draggable(true)
        )
    }
}


问:
Trying to get to api
I try to get to this api : https://www.football-data.org/. I have key and token name. From Postman I can get to this api by "Api Key" autorization with name : X-Auth-Token and token XXXX. But how can I do this from java with rest template ? How should i put my headers to this url:

```<code>  public List<FootballDto> getFootballs() {
        HttpHeaders headers = new HttpHeaders();
        headers.add(tokenName,token);
        FootballDto[] footballResponse = restTemplate.getForObject(
                "https://api.football-data.org/v2/competitions/SA/scorers", FootballDto[].class
        );
    }
</code>```

Thanks a lot :)

答:
The RestTemplate getForObject() method doesn't support setting headers. The solution is to use the exchange() method. So instead of restTemplate.getForObject(url, String.class, param) (which has no headers), use:

```<code> HttpHeaders headers = new HttpHeaders();
 headers.set("Header-1", "value-1");
 headers.set("Header-2", "value-2");
 ...

 HttpEntity entity = new HttpEntity(headers);

 ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class, param);
</code>```

Finally, use response.getBody() to get your result.

Title: Trying to get to api

Body:
I try to get to this api : https://www.football-data.org/. I have key and token name. From Postman I can get to this api by "Api Key" autorization with name : X-Auth-Token and token XXXX. But how can I do this from java with rest template ? How should i put my headers to this url:

  public List<FootballDto> getFootballs() {
        HttpHeaders headers = new HttpHeaders();
        headers.add(tokenName,token);
        FootballDto[] footballResponse = restTemplate.getForObject(
                "https://api.football-data.org/v2/competitions/SA/scorers", FootballDto[].class
        );
    }

Thanks a lot :)

Body:
The RestTemplate getForObject() method doesn't support setting headers. The solution is to use the exchange() method. So instead of restTemplate.getForObject(url, String.class, param) (which has no headers), use:

 HttpHeaders headers = new HttpHeaders();
 headers.set("Header-1", "value-1");
 headers.set("Header-2", "value-2");
 ...

 HttpEntity entity = new HttpEntity(headers);

 ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class, param);

Finally, use response.getBody() to get your result.


问:
Send a POST request with an image URL? --- Needle library
Trying to figure out the right way to send a RESTful request to an API using the Node.js Needle library. I think everything is right except the code concerning the image URL. No matter how I try to change what it looks like or where I put it, I keep getting an error that says it's an invalid image, but it's not, the URL is fine. So, my guess is my code is wrong and so whatever it thinks is the URL for the image, is probably not the URL (but maybe some other code or code in a location that should be where the body/image URL is).

```<code>const imageUrl = 'https://upload.wikimedia.org/wikipedia/commons/3/37/Dagestani_man_and_woman.jpg'

// Request parameters.
const params = {
    returnFaceId: true,
    returnFaceLandmarks: false,
    returnFaceAttributes: 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise'
}

var options = {
    body: '{"url": ' + '"' + imageUrl + '"}',
    headers: {
        'Content-Type': 'application/json',
        'Ocp-Apim-Subscription-Key': subscriptionKey
    }
}

needle.post(endpoint, params, options, function (err, res, body) {
    console.log(`Status: ${res.statusCode}`)
    console.log('Body: ', body)
    console.log('ERROR: ' + err)
    //console.log(res)
})
</code>```

I have also tried to write the body like a plain ol' object: body = { 'url': imageURL}, but still getting the same error.

Error:

```<code>Status: 400
Body:  { error: { code: 'InvalidURL', message: 'Invalid image URL.' } }
</code>```

Here is the API I am trying to call, which has been confirmed to work with other samples:
https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395236

答:
For this request you have a combination of parameters:

Some of them as query strings (your 'params')

Some of them as a body payload (your options.body)

Therefore, it seems that you cannot use needle.post directly because it can do query string params OR body param but not both at the same time.

So there are several options:

Set your query string params in the URL field

Change your lib

For the 1st option, here is an example:

```<code>const imageUrl = 'https://upload.wikimedia.org/wikipedia/commons/3/37/Dagestani_man_and_woman.jpg'

// Request parameters.
const params = {
    returnFaceId: true,
    returnFaceLandmarks: false,
    returnFaceAttributes: 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise'
}

// Adding params to query string
serialize = function(obj) {
    var str = [];
    for (var p in obj)
      if (obj.hasOwnProperty(p)) {
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
      }
    return str.join("&");
}

endpoint = endpoint + "?" + serialize(params)

// Setting body and options
var body = '{ "url": ' + '"' + imageUrl + '"}'

var options = {
    headers: {
        'Content-Type': 'application/json',
        'Ocp-Apim-Subscription-Key': subscriptionKey
    }
}

needle.post(endpoint, body, options, function (err, res, body) {
    console.log(`Status: ${res.statusCode}`)
    console.log('Body: ', body)
    console.log('ERROR: ' + err)
    //console.log(res)
})
</code>```

Body:
Trying to figure out the right way to send a RESTful request to an API using the Node.js Needle library. I think everything is right except the code concerning the image URL. No matter how I try to change what it looks like or where I put it, I keep getting an error that says it's an invalid image, but it's not, the URL is fine. So, my guess is my code is wrong and so whatever it thinks is the URL for the image, is probably not the URL (but maybe some other code or code in a location that should be where the body/image URL is).

const imageUrl = 'https://upload.wikimedia.org/wikipedia/commons/3/37/Dagestani_man_and_woman.jpg'

// Request parameters.
const params = {
    returnFaceId: true,
    returnFaceLandmarks: false,
    returnFaceAttributes: 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise'
}

var options = {
    body: '{"url": ' + '"' + imageUrl + '"}',
    headers: {
        'Content-Type': 'application/json',
        'Ocp-Apim-Subscription-Key': subscriptionKey
    }
}

needle.post(endpoint, params, options, function (err, res, body) {
    console.log(`Status: ${res.statusCode}`)
    console.log('Body: ', body)
    console.log('ERROR: ' + err)
    //console.log(res)
})

I have also tried to write the body like a plain ol' object: body = { 'url': imageURL}, but still getting the same error.

Error:

Status: 400
Body:  { error: { code: 'InvalidURL', message: 'Invalid image URL.' } }

Here is the API I am trying to call, which has been confirmed to work with other samples:
https://westus.dev.cognitive.microsoft.com/docs/services/563879b61984550e40cbbe8d/operations/563879b61984550f30395236

Body:
For this request you have a combination of parameters:

Some of them as query strings (your 'params')

Some of them as a body payload (your options.body)

Therefore, it seems that you cannot use needle.post directly because it can do query string params OR body param but not both at the same time.

So there are several options:

Set your query string params in the URL field

Change your lib

For the 1st option, here is an example:

const imageUrl = 'https://upload.wikimedia.org/wikipedia/commons/3/37/Dagestani_man_and_woman.jpg'

// Request parameters.
const params = {
    returnFaceId: true,
    returnFaceLandmarks: false,
    returnFaceAttributes: 'age,gender,headPose,smile,facialHair,glasses,emotion,hair,makeup,occlusion,accessories,blur,exposure,noise'
}

// Adding params to query string
serialize = function(obj) {
    var str = [];
    for (var p in obj)
      if (obj.hasOwnProperty(p)) {
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
      }
    return str.join("&");
}

endpoint = endpoint + "?" + serialize(params)

// Setting body and options
var body = '{ "url": ' + '"' + imageUrl + '"}'

var options = {
    headers: {
        'Content-Type': 'application/json',
        'Ocp-Apim-Subscription-Key': subscriptionKey
    }
}

needle.post(endpoint, body, options, function (err, res, body) {
    console.log(`Status: ${res.statusCode}`)
    console.log('Body: ', body)
    console.log('ERROR: ' + err)
    //console.log(res)
})


问:
How to Fetch Woo Commerce Product Categories icons with names with get_term(product_cat) or something else .. can i fetch only name?
```<code><?php
$orderby = 'id';
$order = 'asc';
$hide_empty = false ;
$cat_args = array(
    'orderby'    => $orderby,
    'order'      => $order,
    'hide_empty'=> 0,
);

$product_categories = get_terms( 'product_cat', $cat_args );

if( !empty($product_categories) ){
    echo '
<ul class="display-categories list-group nav navbar-nav">';
    foreach ($product_categories as $key => $category) {
        echo '
<li class="list-group-item">';
        echo '<a href="'.get_term_link($category).'" >';
        echo '<img src="'.get_term_link($category).'" />' ;
        echo $category->name;
        echo '</a>';
        echo '</li>';
    }
    echo '</ul>';
}
?>
</code>```

<p>I can't fetch the product category icons.. i want it to fetch category icons with the list of names ... please somebody help me out with this thanks  </p>

答:
Category Icons / Images has been stored in terms meta and can be retrieved by using </p>

```<code>$term_meta = get_woocommerce_term_meta( $category_id, 'thumbnail_id', true );
$category_icon = wp_get_attachment_url( $term_meta );
</code>```

Body:
<?php
$orderby = 'id';
$order = 'asc';
$hide_empty = false ;
$cat_args = array(
    'orderby'    => $orderby,
    'order'      => $order,
    'hide_empty'=> 0,
);

$product_categories = get_terms( 'product_cat', $cat_args );

if( !empty($product_categories) ){
    echo '

';
    foreach ($product_categories as $key => $category) {
        echo '

';
        echo '';
        echo '' ;
        echo $category->name;
        echo '';
        echo '
';
    }
    echo '
';
}
?>

I can't fetch the product category icons.. i want it to fetch category icons with the list of names ... please somebody help me out with this thanks

Body:
Category Icons / Images has been stored in terms meta and can be retrieved by using

$term_meta = get_woocommerce_term_meta( $category_id, 'thumbnail_id', true );
$category_icon = wp_get_attachment_url( $term_meta );


问:
Swift getting element type of generic array

How to determine that Swift Generic is an array?

How to instantiate an array of specific elements?

I think I ended solutions.
Thanks for any help.

In a similar situation:

```<code>var value: Any?
</code>```

```<code>func get() -> T? {

    switch T.self {

    case is Int:
        return Int(self.value) as? T

    case let MT as MyProtocol.Type:

        return MT.init(self.value) as? T // Perfectly

    case let MTA as Array<MyProtocol>.Type: // <== Never case, why?

        let values = self.valueAsEEArray()
        return values?.map { TMA.Element.init($0) } as? T
//                                       ^ Protocol type 'Array<MyProtocol>.Element' (aka 'MyProtocol') cannot be instantiated
</code>```

```<code>protocol MyProtocol {
    init(_ value: EE)
}
</code>```

答:
All you need is just write down one more function with return type array of T:</p>

```<code>func get() -> [T] {
  //Code
}
</code>```

Body:
How to determine that Swift Generic is an array?

How to instantiate an array of specific elements?

I think I ended solutions.
Thanks for any help.

In a similar situation:

var value: Any?

func get() -> T? {

    switch T.self {

    case is Int:
        return Int(self.value) as? T

    case let MT as MyProtocol.Type:

        return MT.init(self.value) as? T // Perfectly

    case let MTA as Array<MyProtocol>.Type: // <== Never case, why?

        let values = self.valueAsEEArray()
        return values?.map { TMA.Element.init($0) } as? T
//                                       ^ Protocol type 'Array<MyProtocol>.Element' (aka 'MyProtocol') cannot be instantiated

protocol MyProtocol {
    init(_ value: EE)
}

Body:
All you need is just write down one more function with return type array of T:

func get() -> [T] {
  //Code
}


问:
Exception: Cannot load model.bin
I have got the following error message trying to run a model:

```<code>Exception: fastText: Cannot load model.bin due to C++ extension failed to allocate the memory
</code>```

The code I have used is the following:

```<code>import wget
from fasttext import load_model

wget.download("https://dl.fbaipublicfiles.com/fasttext/supervised-models/amazon_review_polarity.bin", 'model.bin')

model = load_model("model.bin")
</code>```

I have tried to follow this answer: FastText - Cannot load model.bin due to C++ extension failed to allocate the memory but probably I am doing something wrong as the error is still there.
Any idea on how to fix it?

答:
Install the latest version of fasttext (0.9.2) following these steps:

```<code>git clone https://github.com/facebookresearch/fastText.git
cd fastText
pip install .
</code>```

then try to execute your code. It should work.

Title: Exception: Cannot load model.bin

Body:
I have got the following error message trying to run a model:

Exception: fastText: Cannot load model.bin due to C++ extension failed to allocate the memory

The code I have used is the following:

import wget
from fasttext import load_model

wget.download("https://dl.fbaipublicfiles.com/fasttext/supervised-models/amazon_review_polarity.bin", 'model.bin')

model = load_model("model.bin")

I have tried to follow this answer: FastText - Cannot load model.bin due to C++ extension failed to allocate the memory but probably I am doing something wrong as the error is still there.
Any idea on how to fix it?

Body:
Install the latest version of fasttext (0.9.2) following these steps:

git clone https://github.com/facebookresearch/fastText.git
cd fastText
pip install .

then try to execute your code. It should work.