问:
Typescript: Get key from object with indexed signature
I'm importing the following type and function from a TypeScript module:

```<code>type Attributes = {
  [key: string]: number;
};

function Fn<KeysOfAttributes extends string>(opts: { attributes: Attributes }): any {
  // ...
}
</code>```

I can't modify the code above.

Then I implement the following code to my own module:

```<code>// variant 1
const attributes = { // this object is hard coded (not dynamically generated)
  foo: 1,
  bar: 2,
  baz: 3
};

type Type = typeof attributes;
type Keys = keyof Type;

Fn<Keys>({
  attributes
});
</code>```

Everything works perfect. Now I want to assign the type Attributes type to the constant attribute, because I want to be sure that the keys are string and the values are numbers. So I modify my code:

```<code>// variant 2
const attributes: Attributes = {
  foo: 1,
  bar: 2,
  baz: 3
};

type Type = typeof attributes;// equals {[key: string]: number;}
type Keys = keyof Type;// equals string | number. Why ?

Fn<Keys>({// Here, I would like Keys to be "foo" | "bar" | "baz", instead I have string | number
  attributes
});
</code>```

I get the following error on the Fn<Keys>({ line:

```<code>Type 'string | number' does not satisfy the constraint 'string'.
Type 'number' is not assignable to type 'string'.ts(2344)
</code>```

I don't understand why the type Keys equals string | number, when the index signature specifically specifies that the key is a string?

How can I ensure that the "foo" | "bar" | "baz" type gets passed as a type argument instead of string | number?

I can live with the first variant, but I don't understand why the second one doesn't work.
Any idea?

Many thanks

答:
How can I ensure that the "foo" | "bar" | "baz" type gets passed as a type argument instead of string | number?

You can achieve this by introducing generic type parameter for attributes:

```<code>type Attributes = {
  [key: string]: number;
};

function Fn<KeysOfAttributes extends keyof T, T extends Attributes>(opts: { attributes: T }): any {
  // ...
}

const attributes = {
  foo: 1,
  bar: 2,
  baz: 3,
};

Fn({
  attributes
});
</code>```

Typescript will be able to infer the types on its own, so you won't even need the Type and Keys

Playground

Body:
I'm importing the following type and function from a TypeScript module:

type Attributes = {
  [key: string]: number;
};

function Fn<KeysOfAttributes extends string>(opts: { attributes: Attributes }): any {
  // ...
}

I can't modify the code above.

Then I implement the following code to my own module:

// variant 1
const attributes = { // this object is hard coded (not dynamically generated)
  foo: 1,
  bar: 2,
  baz: 3
};

type Type = typeof attributes;
type Keys = keyof Type;

Fn<Keys>({
  attributes
});

Everything works perfect. Now I want to assign the type Attributes type to the constant attribute, because I want to be sure that the keys are string and the values are numbers. So I modify my code:

// variant 2
const attributes: Attributes = {
  foo: 1,
  bar: 2,
  baz: 3
};

type Type = typeof attributes;// equals {[key: string]: number;}
type Keys = keyof Type;// equals string | number. Why ?

Fn<Keys>({// Here, I would like Keys to be "foo" | "bar" | "baz", instead I have string | number
  attributes
});

I get the following error on the Fn<Keys>({ line:

Type 'string | number' does not satisfy the constraint 'string'.
Type 'number' is not assignable to type 'string'.ts(2344)

I don't understand why the type Keys equals string | number, when the index signature specifically specifies that the key is a string?

How can I ensure that the "foo" | "bar" | "baz" type gets passed as a type argument instead of string | number?

I can live with the first variant, but I don't understand why the second one doesn't work.
Any idea?

Many thanks

Body:
How can I ensure that the "foo" | "bar" | "baz" type gets passed as a type argument instead of string | number?

You can achieve this by introducing generic type parameter for attributes:

type Attributes = {
  [key: string]: number;
};

function Fn<KeysOfAttributes extends keyof T, T extends Attributes>(opts: { attributes: T }): any {
  // ...
}

const attributes = {
  foo: 1,
  bar: 2,
  baz: 3,
};

Fn({
  attributes
});

Typescript will be able to infer the types on its own, so you won't even need the Type and Keys

<a href="https://www.typescriptlang.org/play/index.html#src=type%20Attributes%20%3D%20%7B%0D%0A%20%20%5Bkey%3A%20string%5D%3A%20number%3B%0D%0A%7D%3B%0D%0A%0D%0Afunction%20Fn%3CKeysOfAttributes%20extends%20keyof%20T%2C%20T%20extends%20Attributes%3E(opts%3A%20%7B%20attributes%3A%20T%20%7D)%3A%20any%20%7B%0D%0A%20%20%2F%2F%20...%0D%0A%7D%0D%0A%0D%0Aconst%20attributes%20%3D%20%7B%0D%0A%20%20foo%3A%201%2C%0D%0A%20%20bar%3A%202%2C%0D%0A%20%20baz%3A%203%2C%0D%0A%7D%3B%0D%0A%0D%0AFn(%7B%0D%0A%20%20attributes%0D%0A%7D)%3B" rel="nofollow noreferrer">Playground


来源: stackexchange

问:
Using GORM and Postgresql how to set the search_path?
How can I get the current schema from gorm?  Normally it is "SHOW search_path" and is an exec.  Same with setting the current search_path  normally "set search_path to newschema". where new schema can be a single schema name of a series of names.

I attempted db.Exec("show search_path").Find(&result) where result is a []string and I get an empty array.

答:
FOUND how to display current schema by experimenting and a hint about Raw and Scan in PluralSite's GORM class.

```<code>var currentSchema string
rows, err := db.Debug().Raw("show search_path").Rows()
rows.Next()  // to get the first and only result
rows.Scan(&currentSchema)
fmt.Printf("Search Path: %v\n", currentSchema)
</code>```

returns: Search Path: "$user", public

Taking @PavloStrokov point about transactions (which are basically threads and a transaction) into account, I was able to get the schema to stay during the current process. In the handler, I use the existing DB connection and create a transaction. It gets passed to every method that is called that touches the Database. I change the call to the gorm method to be the passed tx instead of the normal db variable that was stored and made available to any method that needed it.

The call I make to start it all of is:

tx := db.Begin()

tx.Exec("set search_path to schema_name")

The string is generated to use the proper Facility schema name.

The tx is the last param in the signature of all methods that touch the DB. For example func methiodUsingDBSchema(val1 string, val2 string,  tx *gorm.DB){}

Then the last thing I do is tx.Commit()  Even though these are all reads.

I have run all test and works well.

I use the Postgres schemas to separate Facilities in my application and need to change based upon the user logged in.  All User and Facility information is in public.

ContentLicense: CC BY-SA 4.0

Body:
FOUND how to display current schema by experimenting and a hint about Raw and Scan in PluralSite's GORM class.

var currentSchema string
rows, err := db.Debug().Raw("show search_path").Rows()
rows.Next()  // to get the first and only result
rows.Scan(&currentSchema)
fmt.Printf("Search Path: %v\n", currentSchema)

returns: Search Path: "$user", public

Taking @PavloStrokov point about transactions (which are basically threads and a transaction) into account, I was able to get the schema to stay during the current process. In the handler, I use the existing DB connection and create a transaction. It gets passed to every method that is called that touches the Database. I change the call to the gorm method to be the passed tx instead of the normal db variable that was stored and made available to any method that needed it.

The call I make to start it all of is:

tx := db.Begin()

tx.Exec("set search_path to schema_name")

The string is generated to use the proper Facility schema name.

The tx is the last param in the signature of all methods that touch the DB. For example func methiodUsingDBSchema(val1 string, val2 string,  tx *gorm.DB){}

Then the last thing I do is tx.Commit()  Even though these are all reads.

I have run all test and works well.

I use the Postgres schemas to separate Facilities in my application and need to change based upon the user logged in.  All User and Facility information is in public.


问:
I want to install sass using npm, but it throws err: Cannot find module "semver"
I am trying to install sass with the following command:

npm install node-sass --save-dev

But I am receiving the following error:

```<code>internal/modules/cjs/loader.js:626
    throw err;
    ^

Error: Cannot find module 'semver'
Require stack:
- /usr/share/npm/lib/utils/unsupported.js
- /usr/share/npm/bin/npm-cli.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:623:15)
    at Function.Module._load (internal/modules/cjs/loader.js:527:27)
    at Module.require (internal/modules/cjs/loader.js:681:19)
    at require (internal/modules/cjs/helpers.js:16:16)
    at Object.<anonymous> (/usr/share/npm/lib/utils/unsupported.js:2:14)
    at Module._compile (internal/modules/cjs/loader.js:774:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:785:10)
    at Module.load (internal/modules/cjs/loader.js:641:32)
    at Function.Module._load (internal/modules/cjs/loader.js:556:12)
    at Module.require (internal/modules/cjs/loader.js:681:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/usr/share/npm/lib/utils/unsupported.js',
    '/usr/share/npm/bin/npm-cli.js'
  ]
}
</code>```

I have tried uninstalling/reinstalling npm but this didn't resolve my error.

So I have tried the following to see if this would help:

```<code>sudo rm -rf /usr/lib/node_modules/
sudo rm -rf ~/.npm
brew uninstall --force node
brew install node
</code>```

But the error still persists.. Any help would be greatly appreciated!

答:
Perhaps you could try the following steps and seeing if they resolve your issue:

Remove your package-lock.json file if it exists. It may have gotten out of sorts and is causing locking issues for npm.

rm package-lock.json

Retry the steps you listed, but instead of removing the node_modules directory from  the /usr/lib/node_modules directory try removing the node_modules directory from  /usr/local/lib/node_modules directory.

The steps would be as follows, for more detailed information see this answer:

```<code>sudo rm -rf /usr/local/lib/node_modules
sudo rm -rf ~/.npm
brew uninstall --force node
brew install node
</code>```

Lastly, if all else fails try installing Node from official documentation

Hopefully that helps!

Body:
I am trying to install sass with the following command:

npm install node-sass --save-dev

But I am receiving the following error:

internal/modules/cjs/loader.js:626
    throw err;
    ^

Error: Cannot find module 'semver'
Require stack:
- /usr/share/npm/lib/utils/unsupported.js
- /usr/share/npm/bin/npm-cli.js
    at Function.Module._resolveFilename (internal/modules/cjs/loader.js:623:15)
    at Function.Module._load (internal/modules/cjs/loader.js:527:27)
    at Module.require (internal/modules/cjs/loader.js:681:19)
    at require (internal/modules/cjs/helpers.js:16:16)
    at Object.<anonymous> (/usr/share/npm/lib/utils/unsupported.js:2:14)
    at Module._compile (internal/modules/cjs/loader.js:774:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:785:10)
    at Module.load (internal/modules/cjs/loader.js:641:32)
    at Function.Module._load (internal/modules/cjs/loader.js:556:12)
    at Module.require (internal/modules/cjs/loader.js:681:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/usr/share/npm/lib/utils/unsupported.js',
    '/usr/share/npm/bin/npm-cli.js'
  ]
}

I have tried uninstalling/reinstalling npm but this didn't resolve my error.

So I have tried the following to see if this would help:

sudo rm -rf /usr/lib/node_modules/
sudo rm -rf ~/.npm
brew uninstall --force node
brew install node

But the error still persists.. Any help would be greatly appreciated!

Body:
Perhaps you could try the following steps and seeing if they resolve your issue:

Remove your package-lock.json file if it exists. It may have gotten out of sorts and is causing locking issues for npm.

rm package-lock.json

Retry the steps you listed, but instead of removing the node_modules directory from  the /usr/lib/node_modules directory try removing the node_modules directory from  /usr/local/lib/node_modules directory.

The steps would be as follows, for more detailed information see this answer:

sudo rm -rf /usr/local/lib/node_modules
sudo rm -rf ~/.npm
brew uninstall --force node
brew install node

Lastly, if all else fails try installing Node from official documentation

Hopefully that helps!


问:
Excel VBA Dir() Error when file type changes
I'm trying to better understand the Dir function. I have a Dir loop to take action on all .csv files in the directory, but when the loop comes across another file type, like .txt, it will error instead of moving on to the next .csv. item.

This is the relevant portion of my code.

```<code>strSourceExcelLocation = "\\rilinfs001\Interdepartmental\Billings & Deductions\Billing Coordinators\MCB Reports\East\Monthly Quality MCBs (CMQ & SECMQ)\2019\Individual_Reports\" & fldr & "\"

strWorkbook = Dir(strSourceExcelLocation & "*.csv*")

Do While Len(strWorkbook) > 0
    'Open the workbook
    Set wbktoExport = Workbooks.Open(Filename:=strSourceExcelLocation & strWorkbook)

    'Export all sheets as single PDF
    Call Export_Excel_as_PDF(wbktoExport)

    'Get next workbook
    strWorkbook = Dir

    'Close Excel workbook without making changes
    wbktoExport.Close False
Loop
</code>```

So if there are only  .csv files in the directory, then this works fine. When it comes across another file type, an error occurs.

The error is on line

```<code>strWorkbook = Dir
</code>```

Run-time error 5: Invalid procedure call or argument

Am I missing something with the way I use the wildcards in the .csv at the beginning?

Thank you

答:
Solved my issue.

The problem seems to have been because when I called another procedure, I had another Dir in that sub to create a new folder if one didn't already exist. So basically I had a Dir in a Dir, which apparently is bad.

I moved the folder creation part to the very beginning of my procedure, so it is executed before I begin the Dir for looping through all the CSV files.

```<code>Option Explicit

Sub Loop_Dir_for_Excel_Workbooks()
Dim strWorkbook As String, wbktoExport As Workbook, strSourceExcelLocation As String, fldr As String, strTargetPDFLocation As String, d As String

strTargetPDFLocation = "\\nhchefs001\Accounting\IMAGING\BILLINGS & DEDUCTIONS\EAST MCB FILES\"
'***** Creating a folder to save the PDFs in. Naming the folder with today's date *****
d = Format(Date, "mm-dd-yyyy")
strTargetPDFLocation = "\\nhchefs001\Accounting\IMAGING\BILLINGS & DEDUCTIONS\EAST MCB FILES\" & d & "\"
If Len(Dir(strTargetPDFLocation, vbDirectory)) = 0 Then MkDir strTargetPDFLocation

fldr = InputBox("Input the EXACT Folder Name that you want to create PDFs for")

strSourceExcelLocation = "\\rilinfs001\Interdepartmental\Billings & Deductions\Billing Coordinators\MCB Reports\East\Monthly Quality MCBs (CMQ & SECMQ)\2019\Individual_Reports\" & fldr & "\"

'Search all Excel files in the directory with .xls, .xlsx, xlsm extensions
strWorkbook = Dir(strSourceExcelLocation & "*.csv")

Do While Len(strWorkbook) > 0
    'Open the workbook
    Set wbktoExport = Workbooks.Open(Filename:=strSourceExcelLocation & strWorkbook)

    'Export all sheets as single PDF
    Call Export_Excel_as_PDF(wbktoExport, strTargetPDFLocation)

    'Close Excel workbook without making changes
    wbktoExport.Close False

    'Get next workbook
    strWorkbook = Dir

Loop

End Sub
</code>```

Body:
I'm trying to better understand the Dir function. I have a Dir loop to take action on all .csv files in the directory, but when the loop comes across another file type, like .txt, it will error instead of moving on to the next .csv. item.

This is the relevant portion of my code.

strSourceExcelLocation = "\\rilinfs001\Interdepartmental\Billings & Deductions\Billing Coordinators\MCB Reports\East\Monthly Quality MCBs (CMQ & SECMQ)\2019\Individual_Reports\" & fldr & "\"

strWorkbook = Dir(strSourceExcelLocation & "*.csv*")

Do While Len(strWorkbook) > 0
    'Open the workbook
    Set wbktoExport = Workbooks.Open(Filename:=strSourceExcelLocation & strWorkbook)

    'Export all sheets as single PDF
    Call Export_Excel_as_PDF(wbktoExport)

    'Get next workbook
    strWorkbook = Dir

    'Close Excel workbook without making changes
    wbktoExport.Close False
Loop

So if there are only  .csv files in the directory, then this works fine. When it comes across another file type, an error occurs.

The error is on line

strWorkbook = Dir

Run-time error 5: Invalid procedure call or argument

Am I missing something with the way I use the wildcards in the .csv at the beginning?

Thank you

Body:
Solved my issue.

The problem seems to have been because when I called another procedure, I had another Dir in that sub to create a new folder if one didn't already exist. So basically I had a Dir in a Dir, which apparently is bad.

I moved the folder creation part to the very beginning of my procedure, so it is executed before I begin the Dir for looping through all the CSV files.

Option Explicit

Sub Loop_Dir_for_Excel_Workbooks()
Dim strWorkbook As String, wbktoExport As Workbook, strSourceExcelLocation As String, fldr As String, strTargetPDFLocation As String, d As String

strTargetPDFLocation = "\\nhchefs001\Accounting\IMAGING\BILLINGS & DEDUCTIONS\EAST MCB FILES\"
'***** Creating a folder to save the PDFs in. Naming the folder with today's date *****
d = Format(Date, "mm-dd-yyyy")
strTargetPDFLocation = "\\nhchefs001\Accounting\IMAGING\BILLINGS & DEDUCTIONS\EAST MCB FILES\" & d & "\"
If Len(Dir(strTargetPDFLocation, vbDirectory)) = 0 Then MkDir strTargetPDFLocation

fldr = InputBox("Input the EXACT Folder Name that you want to create PDFs for")

strSourceExcelLocation = "\\rilinfs001\Interdepartmental\Billings & Deductions\Billing Coordinators\MCB Reports\East\Monthly Quality MCBs (CMQ & SECMQ)\2019\Individual_Reports\" & fldr & "\"

'Search all Excel files in the directory with .xls, .xlsx, xlsm extensions
strWorkbook = Dir(strSourceExcelLocation & "*.csv")

Do While Len(strWorkbook) > 0
    'Open the workbook
    Set wbktoExport = Workbooks.Open(Filename:=strSourceExcelLocation & strWorkbook)

    'Export all sheets as single PDF
    Call Export_Excel_as_PDF(wbktoExport, strTargetPDFLocation)

    'Close Excel workbook without making changes
    wbktoExport.Close False

    'Get next workbook
    strWorkbook = Dir

Loop

End Sub


问:
How to display db results as options in HTML dropdown with PHP and Mysqli?
I am trying to to let users choose the state filed from a drop down in the form, but although the query works, the DB is connected, the drop down does not display the list.

Not sure if relevant but i'm running Windows Server, IIS 10 and the latest PHP and MySql.

    State
    <select class="form-control" name="state" id="state">

    <?php
    // Query to find STATE
    $sql1 = "SELECT * FROM codetable WHERE category = 'state'";
    $result1 = $conn->query($sql1);

    $row1 = mysqli_fetch_array($result1);

    while($row1 = mysqli_fetch_array($result1))
        {
            echo '<option value=" '.$row1['code'].' "> '.$row1['description'].' </option>';
         }
     ?>
    </select>

```

I expect the list from the DB to be in the dropdown, but it is empty (No dropdown list).

答:
Get rid of $row1 = mysqli_fetch_array($result1); before your while loop and replace the loop with this...

```<code>while($row1 = mysqli_fetch_array($result1))
{
    ?>
        <option value="<?php echo $row1['code']; ?>"><?php echo $row1['description']; ?></option>
    <?php
}
</code>```

Echoing HTML isn't a good practice. Break it up with PHP tags when possible, it'll make your code much easier to debug.

Body:
I am trying to to let users choose the state filed from a drop down in the form, but although the query works, the DB is connected, the drop down does not display the list.

Not sure if relevant but i'm running Windows Server, IIS 10 and the latest PHP and MySql.

    State
    <select class="form-control" name="state" id="state">

    <?php
    // Query to find STATE
    $sql1 = "SELECT * FROM codetable WHERE category = 'state'";
    $result1 = $conn->query($sql1);

    $row1 = mysqli_fetch_array($result1);

    while($row1 = mysqli_fetch_array($result1))
        {
            echo '<option value=" '.$row1['code'].' "> '.$row1['description'].' </option>';
         }
     ?>
    </select>

I expect the list from the DB to be in the dropdown, but it is empty (No dropdown list).

Body:
Get rid of $row1 = mysqli_fetch_array($result1); before your while loop and replace the loop with this...

while($row1 = mysqli_fetch_array($result1))
{
    ?>
        <option value="<?php echo $row1['code']; ?>"><?php echo $row1['description']; ?></option>
    <?php
}

Echoing HTML isn't a good practice. Break it up with PHP tags when possible, it'll make your code much easier to debug.


问:
Google Maps, Bing Maps, OpenStreetMaps and MapQuest limitation
I'm very confused reading the online term of use of some Online Map Service (like Google Maps, Bing Maps, OpenStreetMaps and Mapquest)...

There is a way to use Google or Bing Maps on a website for non-commercial or commercial pourpose without any daily limitation of request?? What kind of Api I can use for free without any limitation of use or request, if I want to see a map on my site with several point of interest inserted by me??

I have read that in free version of Google or Bing some ads may appear sometimes inside the maps, and I cannot insert in my webpages any ads from another provider different from Google or Bing. It's true?

If I want to use OpenStreetMaps (an opensource Maps Database) or the partner MapQuest, it's true that there aren't any limitations of daily request or appearing ads on the maps or policy of exclusive banner campaign??

But, at the end, If I try to build a portal with this maps, and I want to plan in the future the insertion of some ads and the creation of a little company, I'm doing a commercial or not-commercial use (now and in future)??

答:
Google recently announced new advertising and rate limiting in their terms of service. Websites will be forced to display ads in their maps, or pay for a premium account. Popular websites (resulting in lots of hits of google map tile server) will also need to pay for a premium account. It's not clear if your intended use will trigger those limits.

OpenStreetMap might offer a viable alternative. They do run a map tile server which can be used to embed a slippy map on your website. There is also an open source javascript library called OpenLayers (among other options), meaning that you can be free of google and their ads. OpenStreetMap do however operate a strict tile usage policy to protect the service which is paid for by donations, and run by volunteers.

OpenStreetMap also uniquely offers another approach: Create your own tile server, rendering the raw map data yourself. This might be a sensible option if you run a very popular website, or if you require only a limited area of the world to be shown. It's also really neat because you have full control over rendering style. It's a fairly technical process though ...but

Because this is possible, a number of third parties will offer you a map tile service built using OpenStreetMap data. e.g. MapQuest, CloudMade, TileServer,  TileDrawer, or MapBox

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Show() method will not show .gif in picturebox that was hidden a second ago
Okay so I have created a Flowlayoutpanel in which about 70 usercontrols, all squares of 50x50 pixels with an animated grass gif inside a picturebox inside of it. I want to make these hide-able but not be removed so there's a white space left. I've been able to do that quite consistently by just using Hide() and changing the background colour to be transparant so I don't have to hide the entire UserControl.

Problem comes up here, I want these gifs to reappear on a timer, so I've created a timer that references a method which just uses a show() again to show said gif and yet it refuses to do so if I create a seperate button to do so or not.

I have searched quite a bit but I think this is a problem only because I'm consistently missing something in my code so no other question really seems to answer my troubles. Because it's such a simple question I feel kind of embarrassed even asking it but oh well.

This is the timer event that calls the method in the other class

```<code>private void GrasTerugkeerTimer_Tick(object sender, EventArgs e)
        {
            var instance = new GrasVeldUC();
            instance.TerugKeerGras();
        }
</code>```

This is the events and methods I've set up to show and hide the picturebox that the gif is inside of

```<code> public partial class GrasVeldUC : UserControl
    {
        public GrasVeldUC()
        {
            InitializeComponent();
            this.BackColor = Color.White;
        }

        private void GrasVeldUC_Click(object sender, EventArgs e)
        {
            this.BackColor = Color.FromArgb(0, 255, 255, 255);
            PIBGrasUC.Hide();
        }

        private void PIBGrasUC_Click(object sender, EventArgs e)
        {
            this.BackColor = Color.FromArgb(0, 255, 255, 255);
            PIBGrasUC.Hide();
        }
        public void TerugKeerGras()
        {
            this.BackColor = Color.FromArgb(100, 255, 255, 255);
            PIBGrasUC.Show();
        }
    }
</code>```

Now I expected this to just work and just show the picturebox again and yet whatever I tried, creating a seperate method that references the method in the other class, it would not work. And the method in the class "GrasVeldUC" does work I put a messagebox inside of it to test and it worked perfectly.

答: You can just toggle the picturebox.visible as needed.

Body:
Okay so I have created a Flowlayoutpanel in which about 70 usercontrols, all squares of 50x50 pixels with an animated grass gif inside a picturebox inside of it. I want to make these hide-able but not be removed so there's a white space left. I've been able to do that quite consistently by just using Hide() and changing the background colour to be transparant so I don't have to hide the entire UserControl.

Problem comes up here, I want these gifs to reappear on a timer, so I've created a timer that references a method which just uses a show() again to show said gif and yet it refuses to do so if I create a seperate button to do so or not.

I have searched quite a bit but I think this is a problem only because I'm consistently missing something in my code so no other question really seems to answer my troubles. Because it's such a simple question I feel kind of embarrassed even asking it but oh well.

This is the timer event that calls the method in the other class

private void GrasTerugkeerTimer_Tick(object sender, EventArgs e)
        {
            var instance = new GrasVeldUC();
            instance.TerugKeerGras();
        }

This is the events and methods I've set up to show and hide the picturebox that the gif is inside of

 public partial class GrasVeldUC : UserControl
    {
        public GrasVeldUC()
        {
            InitializeComponent();
            this.BackColor = Color.White;
        }

        private void GrasVeldUC_Click(object sender, EventArgs e)
        {
            this.BackColor = Color.FromArgb(0, 255, 255, 255);
            PIBGrasUC.Hide();
        }

        private void PIBGrasUC_Click(object sender, EventArgs e)
        {
            this.BackColor = Color.FromArgb(0, 255, 255, 255);
            PIBGrasUC.Hide();
        }
        public void TerugKeerGras()
        {
            this.BackColor = Color.FromArgb(100, 255, 255, 255);
            PIBGrasUC.Show();
        }
    }

Now I expected this to just work and just show the picturebox again and yet whatever I tried, creating a seperate method that references the method in the other class, it would not work. And the method in the class "GrasVeldUC" does work I put a messagebox inside of it to test and it worked perfectly.


问:
How to prevent HTML5 form validation on non-submit button?
A form with reset and submit buttons, but both are causing HTML5 validation.  When the user clicks reset, I just want the fields cleared.  Assuming this is default action for any form button, and not just submit, how do I prevent the default action, but still run the custom action?

```<code><button data-ng-click="reset()">Reset Form</button>
<input type="submit" data-ng-click="main.$valid && post('Check')" class="submitbtn" value="Submit" />
</code>```

答:
Specify the button's type attribute to button:</p>

```<code><button type="button" data-ng-click="reset()">Reset Form</button>
</code>```

Body:
A form with reset and submit buttons, but both are causing HTML5 validation.  When the user clicks reset, I just want the fields cleared.  Assuming this is default action for any form button, and not just submit, how do I prevent the default action, but still run the custom action?

<button data-ng-click="reset()">Reset Form</button>
<input type="submit" data-ng-click="main.$valid && post('Check')" class="submitbtn" value="Submit" />

Body:
Specify the button's type attribute to button:

<button type="button" data-ng-click="reset()">Reset Form</button>


问:
How to deserialize two different XML types in to one class
I have two different XML documents. Their structure is almost identical, but they have some different elements.

I would like to deserialize the incoming documents in to one class which is a superset of both classes. There is no need to ever serialize the class, I only need to deserialize the documents.

The XML document types have a different root element, lets say the root of the first is <CLASSA>and the other is <CLASSB>.
I am looking for something like this, where both <CLASSA> and <CLASSB> xml documents are mapped to ClassAandB:

```<code>[XmlRoot(ElementName="CLASSA,CLASSB")]
public class ClassAandB {
    [XmlElement(ElementName="syntaxid")]
    public Syntaxid Syntaxid{ get; set; }
    [XmlElement(ElementName="email")]
    public Email Email { get; set; }
    [XmlElement(ElementName="envelope")]
    public Envelope Envelope { get; set; }
    [XmlElement(ElementName="header")]
    public Header Header { get; set; }
}
</code>```

I can then find out which of the two types it is by reading the Syntaxid property. This helps me because a lot of the processing is the same for both types.
Any suggestions how to do this?

答:
Since the xml root element name might depend on the content of the xml document, you'll have to configure the XmlSerializer at runtime with this xml root element name to be used.

In this case, there's no need anymore to apply an XmlRootAttribute.

This can be done via the constructor overload accepting an XmlRootAttribute argument, via which you pass the root element name.

```<code>public XmlSerializer (Type type, System.Xml.Serialization.XmlRootAttribute root);
</code>```

You might know the root element name in front eg. depending on the source of the xml document, or you might discover it at runtime from the xml document itself.

The following from the example below shows how the xml root element name gets set.

```<code>String rootName = "CLASSA"; // "CLASSB"
var serializer = new XmlSerializer(typeof(ClassAandB), new XmlRootAttribute(rootName));
</code>```

An simplified example using an XmlReader as source and retrieving the root xml element name from the content.

```<code>public class ClassAandB
{
    [XmlElement(ElementName="syntaxid")]
    public String Syntaxid{ get; set; }

    [XmlElement(ElementName="email")]
    public String Email { get; set; }

    [XmlElement(ElementName="header")]
    public String Header { get; set; }
}
</code>```

```<code>var classA = Deserialize(XmlReader.Create(
    new StringReader("<CLASSA><syntaxid>A</syntaxid></CLASSA>"))
    );
Console.WriteLine(classA.Syntaxid); // A

var classB = Deserialize(
    XmlReader.Create(new StringReader("<CLASSB><syntaxid>B</syntaxid></CLASSB>"))
    );
Console.WriteLine(classB.Syntaxid); // B
</code>```

```<code>public static ClassAandB Deserialize(XmlReader reader)
{
    reader.MoveToContent();
    string rootName = reader.Name;
    var serializer  = new XmlSerializer(typeof(ClassAandB),
        new XmlRootAttribute(rootName)
        );
    var deserialized = serializer.Deserialize(reader) as ClassAandB;
    return deserialized;
}
</code>```

Body:
I have two different XML documents. Their structure is almost identical, but they have some different elements.

I would like to deserialize the incoming documents in to one class which is a superset of both classes. There is no need to ever serialize the class, I only need to deserialize the documents.

The XML document types have a different root element, lets say the root of the first is <CLASSA>and the other is <CLASSB>.
I am looking for something like this, where both <CLASSA> and <CLASSB> xml documents are mapped to ClassAandB:

[XmlRoot(ElementName="CLASSA,CLASSB")]
public class ClassAandB {
    [XmlElement(ElementName="syntaxid")]
    public Syntaxid Syntaxid{ get; set; }
    [XmlElement(ElementName="email")]
    public Email Email { get; set; }
    [XmlElement(ElementName="envelope")]
    public Envelope Envelope { get; set; }
    [XmlElement(ElementName="header")]
    public Header Header { get; set; }
}

I can then find out which of the two types it is by reading the Syntaxid property. This helps me because a lot of the processing is the same for both types.
Any suggestions how to do this?

Body:
Since the xml root element name might depend on the content of the xml document, you'll have to configure the XmlSerializer at runtime with this xml root element name to be used.

In this case, there's no need anymore to apply an XmlRootAttribute.

This can be done via the constructor overload accepting an XmlRootAttribute argument, via which you pass the root element name.

public XmlSerializer (Type type, System.Xml.Serialization.XmlRootAttribute root);

You might know the root element name in front eg. depending on the source of the xml document, or you might discover it at runtime from the xml document itself.

The following from the example below shows how the xml root element name gets set.

String rootName = "CLASSA"; // "CLASSB"
var serializer = new XmlSerializer(typeof(ClassAandB), new XmlRootAttribute(rootName));

An simplified example using an XmlReader as source and retrieving the root xml element name from the content.

public class ClassAandB
{
    [XmlElement(ElementName="syntaxid")]
    public String Syntaxid{ get; set; }

    [XmlElement(ElementName="email")]
    public String Email { get; set; }

    [XmlElement(ElementName="header")]
    public String Header { get; set; }
}

var classA = Deserialize(XmlReader.Create(
    new StringReader("<CLASSA><syntaxid>A</syntaxid></CLASSA>"))
    );
Console.WriteLine(classA.Syntaxid); // A

var classB = Deserialize(
    XmlReader.Create(new StringReader("<CLASSB><syntaxid>B</syntaxid></CLASSB>"))
    );
Console.WriteLine(classB.Syntaxid); // B

public static ClassAandB Deserialize(XmlReader reader)
{
    reader.MoveToContent();
    string rootName = reader.Name;
    var serializer  = new XmlSerializer(typeof(ClassAandB),
        new XmlRootAttribute(rootName)
        );
    var deserialized = serializer.Deserialize(reader) as ClassAandB;
    return deserialized;
}


问:
PowerShell Multiple Catch Issue
I'm following Microsoft examples and I get an error when I run this in PowerShell (5.1). I am unable to repro this in the ISE.

```<code>$app="notepad2354.exe"
try{
   iex $app
}
catch [System.Management.Automation.CommandNotFoundException]{
   write-host 'ERROR! The app file could not be found.'
}
catch {
   write-host 'ERROR! Unknown error when executing the step. Error: ' + $_.Exception.Message
}
</code>```

Error:

catch : The term 'catch' is not recognized as the name of a cmdlet,
  function, script file, or operable program. Check the spelling of the
  name, or if a path was included, verify that the path is correct and
  try again.

The odd thing is it works fine on the first catch. If I switch the order, the second one always fails with this message.  Any ideas why this is error'ing?

答:
So, it turns out that I can't simply copy and paste that script into a PowerShell command window. It works in the ISE and, as I just found out, it works  inside a Powershell Script file.

My guess is that it processes the try..catch as a batch and doesn't read the entire pasted command before executing. You can work around this issue by making sure the second catch is on the same line as the first catch ends, like so:

```<code>$app="notepad2354.exe"
try{
   iex $app
}
catch [System.Management.Automation.CommandNotFoundException]{
   write-host 'ERROR! The app file could not be found.'
} catch {
   write-host 'ERROR! Unknown error when executing the step. Error: ' + $_.Exception.Message
}
</code>```

Title: PowerShell Multiple Catch Issue

Body:
I'm following Microsoft examples and I get an error when I run this in PowerShell (5.1). I am unable to repro this in the ISE.

$app="notepad2354.exe"
try{
   iex $app
}
catch [System.Management.Automation.CommandNotFoundException]{
   write-host 'ERROR! The app file could not be found.'
}
catch {
   write-host 'ERROR! Unknown error when executing the step. Error: ' + $_.Exception.Message
}

Error:

catch : The term 'catch' is not recognized as the name of a cmdlet,
  function, script file, or operable program. Check the spelling of the
  name, or if a path was included, verify that the path is correct and
  try again.

The odd thing is it works fine on the first catch. If I switch the order, the second one always fails with this message.  Any ideas why this is error'ing?

Body:
So, it turns out that I can't simply copy and paste that script into a PowerShell command window. It works in the ISE and, as I just found out, it works  inside a Powershell Script file.

My guess is that it processes the try..catch as a batch and doesn't read the entire pasted command before executing. You can work around this issue by making sure the second catch is on the same line as the first catch ends, like so:

$app="notepad2354.exe"
try{
   iex $app
}
catch [System.Management.Automation.CommandNotFoundException]{
   write-host 'ERROR! The app file could not be found.'
} catch {
   write-host 'ERROR! Unknown error when executing the step. Error: ' + $_.Exception.Message
}


问:
R - Removing the same name in two columns of a data frame
I am working with a data frame that has two columns, name and spouse. I am trying to calculate the interracial marriage frequency, but I need to remove repeated registers.
When I have the name of a creature I need to keep this register in the data frame but remove the register where that creature name is the spouse name. I have this following data sample:

```<code>                    name                      spouse
15                  Finarfin                  EÃ¤rwen
6             Tar-VanimeldÃ«                  Herucalmo
17                   Faramir                  owyn
8               Tar-Meneldur                  Almarian
14   Finduilas of Dol Amroth                  Denethor II
12                    FinwÃ«                  MÃriel SerindÃ« then ,Indis
9              Tar-AncalimÃ«                  Hallacar
7                Tar-MÃriel                   Ar-PharazÃ´n
5          Tarannon Falastur                  BerÃºthiel
21             Rufus Burrows                  Asphodel Brandybuck
2                     Angrod                  EldalÃ³tÃ«
4               Ar-GimilzÃ´r                  InzilbÃªth
19 Lobelia Sackville-Baggins                  Otho Sackville-Baggins
25            Mrs. Proudfoot                  Odo Proudfoot
22            Rudigar Bolger                  Belba Baggins
24             Odo Proudfoot                  Mrs. Proudfoot
3               Ar-PharazÃ´n                  Tar-MÃriel
13                 Fingolfin                  AnairÃ«
18                SilmariÃ«n                  Elatan
23           Rowan Greenhand                  Belba Baggins
20                     RÃan                   Huor
1                     Adanel                  Belemir
16           Fastolph Bolger                  Pansy Baggins
10         Morwen Steelsheen                  Thengel
11              Tar-Aldarion                  Erendis
25              Belemir                       Adanel
</code>```

For example, I ran the code and in line 1 it caught name Adanel and got Belemir as its spouse, so I need to keep line 1, but remove line 25, because with that I will avoid duplicated data.

I have tried this following code:

```<code>interacialMariage <-data %>% filter(spouse != name) %>% select(name, spouse)
</code>```

How can I get the same spouse name register out of the data frame registers?

P.S.: I would need it to avoid case sensitive (Belemir == belemir) so that I don't have problems in the future.

Thanks!

答:
You could set up another vector with the row-wise alphabetically sorted names, and deduplicate using that...

```<code>sorted <- sapply(1:nrow(data),
                 function(i) paste(sort(c(trimws(tolower(data$name[i])),
                                        trimws(tolower(data$spouse[i])))),
                                   collapse=" "))
irM <- data[!duplicated(sorted),]
</code>```

The trimws strips off any leading or trailing spaces before sorting and pasting, and tolower converts everything to lower case.

Body:
I am working with a data frame that has two columns, name and spouse. I am trying to calculate the interracial marriage frequency, but I need to remove repeated registers.
When I have the name of a creature I need to keep this register in the data frame but remove the register where that creature name is the spouse name. I have this following data sample:

                    name                      spouse
15                  Finarfin                  EÃ¤rwen
6             Tar-VanimeldÃ«                  Herucalmo
17                   Faramir                  owyn
8               Tar-Meneldur                  Almarian
14   Finduilas of Dol Amroth                  Denethor II
12                    FinwÃ«                  MÃriel SerindÃ« then ,Indis
9              Tar-AncalimÃ«                  Hallacar
7                Tar-MÃriel                   Ar-PharazÃ´n
5          Tarannon Falastur                  BerÃºthiel
21             Rufus Burrows                  Asphodel Brandybuck
2                     Angrod                  EldalÃ³tÃ«
4               Ar-GimilzÃ´r                  InzilbÃªth
19 Lobelia Sackville-Baggins                  Otho Sackville-Baggins
25            Mrs. Proudfoot                  Odo Proudfoot
22            Rudigar Bolger                  Belba Baggins
24             Odo Proudfoot                  Mrs. Proudfoot
3               Ar-PharazÃ´n                  Tar-MÃriel
13                 Fingolfin                  AnairÃ«
18                SilmariÃ«n                  Elatan
23           Rowan Greenhand                  Belba Baggins
20                     RÃan                   Huor
1                     Adanel                  Belemir
16           Fastolph Bolger                  Pansy Baggins
10         Morwen Steelsheen                  Thengel
11              Tar-Aldarion                  Erendis
25              Belemir                       Adanel

For example, I ran the code and in line 1 it caught name Adanel and got Belemir as its spouse, so I need to keep line 1, but remove line 25, because with that I will avoid duplicated data.

I have tried this following code:

interacialMariage <-data %>% filter(spouse != name) %>% select(name, spouse)

How can I get the same spouse name register out of the data frame registers?

P.S.: I would need it to avoid case sensitive (Belemir == belemir) so that I don't have problems in the future.

Thanks!

Body:
You could set up another vector with the row-wise alphabetically sorted names, and deduplicate using that...

sorted <- sapply(1:nrow(data),
                 function(i) paste(sort(c(trimws(tolower(data$name[i])),
                                        trimws(tolower(data$spouse[i])))),
                                   collapse=" "))
irM <- data[!duplicated(sorted),]

The trimws strips off any leading or trailing spaces before sorting and pasting, and tolower converts everything to lower case.


问:
sql stores different value then I store
I am using sql server 2005 and .NET.
I have a table with float column named "price".
When I stores 1890 it store 1889.99966796875.

What is the reason?

答:
The reason that floating numbers cannot be mapped to all numbers is because of the mismatch between the decimal and the binary system for fractions.

1889.99966796875 is the number that is the closest to 1890 in this floating point domain, so the closest this number can be reached using binary representation.

Other types, such as decimal and money, use other, much more memory consuming, techniques to store the number (for example , in a string you can store any number, but of course this is not the most performant way to do math)

a simple example  : 0.3 in my own binary system :

```<code>0.1b (inary) would be 0.5 d (ecimal) so too much...
0.01b -->  0.25d (1/4 too little)
0.011 -->  0.375 (1/4 + 1/8 too much)
0.0101 --> 0.3125 (1/4 + 1/16 still too much)
...
0.010011 --> 1/4 +1/32 + 1/64 = 0.296875
</code>```

Suppose my system has 6 bits to represent the fraction, 0.296875 would be the closest for this domain.  The right number cannot be reached due to the decimal/binary system.

For examples see also :
Floating point inaccuracy examples

And an excellent elaborate explenation of your problems is to be found here:
http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html

Another note : it is really about mismatch, not about 'quality' of systems : in decimal notation for example, you cannot represent 1/3 100% accurate, while this would be perfectly possible in other systems.

Title: sql stores different value then I store

Body:
The reason that floating numbers cannot be mapped to all numbers is because of the mismatch between the decimal and the binary system for fractions.

1889.99966796875 is the number that is the closest to 1890 in this floating point domain, so the closest this number can be reached using binary representation.

Other types, such as decimal and money, use other, much more memory consuming, techniques to store the number (for example , in a string you can store any number, but of course this is not the most performant way to do math)

a simple example  : 0.3 in my own binary system :

0.1b (inary) would be 0.5 d (ecimal) so too much...
0.01b -->  0.25d (1/4 too little)
0.011 -->  0.375 (1/4 + 1/8 too much)
0.0101 --> 0.3125 (1/4 + 1/16 still too much)
...
0.010011 --> 1/4 +1/32 + 1/64 = 0.296875

Suppose my system has 6 bits to represent the fraction, 0.296875 would be the closest for this domain.  The right number cannot be reached due to the decimal/binary system.

For examples see also :
Floating point inaccuracy examples

And an excellent elaborate explenation of your problems is to be found here:
http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html

Another note : it is really about mismatch, not about 'quality' of systems : in decimal notation for example, you cannot represent 1/3 100% accurate, while this would be perfectly possible in other systems.


问:
events in fullcalendar/VUE application not updating
Inside of my cal.vue component I have a fullcalendar component. Within cal.vue I have a method called submit. Inside of submit I make a (successful) reference to the fullcalendar component with this.$refs.calendar. However when I do this.$refs.calendar.$emit('refetchEvents'); in my submit function the events are not fetched (my events are not updated on my calendar). Why are my events not being updated upon submit and how can I update them?

Here is the relevant code:

```<code><template>
   <div id="calendar"  :navL="navLinks" :event-sources="eventSources" @event-selected="eventSelected" @event-created="eventCreated" :config="config" >
      <button    class="btn btn-secondary" v-on:click="submit()">
         Submit
      </button>
      <full-calendar id="target" ref="calendar" :event-sources="eventSources" @event-selected="eventSelected" @day-click="click"@event-created="eventCreated" :config="config"></full-calendar>
   </div>
</template>

<script>
   const self = this;
   export default {
      name: 'calendar',
      data() {
         return {
            eventSources: [
               {
                  url: 'http://localhost:3000/getAppointments',
                  type: 'GET',
                  data: {
                     id: this.$store.getters.user
                  },
                  error: function() {
                     alert('there was an error while fetching events!');
                  },
               }
            ],
         };
      },

      methods: {
         submit: function() {
            console.log(this.$refs.calendar); //prints fullcalendar VUE component
            this.$refs.calendar.$emit('refetchEvents'); //nothing appears to happen here
         },
      },
   }
</script>
</code>```

答:
If using the vanilla FullCalendar via npm packages: "@fullcalendar/core", "@fullcalendar/daygrid", "@fullcalendar/timegrid", "@fullcalendar/vue"

```<code>html: <full-calendar ref="fullCalendar" :events="events" />
inside a method to update an event:
        let calendar = this.$refs.fullCalendar.getApi()
        const updatedEvent = calendar.getEventById(eventId)
        updatedEvent.setProp('title', 'New Title')
        updatedEvent.setProp('backgroundColor', 'yellow')
        updatedEvent.setProp('borderColor', 'yellow')
        updatedEvent.setProp('textColor', 'black')
</code>```

The above will rerender the fullCalendar event but will not change your this.events array. There may be something that's a bit more all inclusive for ALL events in one shot otherwise you'd have to do:

```<code>this.events.forEach(event => {
  ...similar code the above
})
</code>```

Body:
Inside of my cal.vue component I have a fullcalendar component. Within cal.vue I have a method called submit. Inside of submit I make a (successful) reference to the fullcalendar component with this.$refs.calendar. However when I do this.$refs.calendar.$emit('refetchEvents'); in my submit function the events are not fetched (my events are not updated on my calendar). Why are my events not being updated upon submit and how can I update them?

Here is the relevant code:

<template>

      <button    class="btn btn-secondary" v-on:click="submit()">
         Submit
      </button>
      <full-calendar id="target" ref="calendar" :event-sources="eventSources" @event-selected="eventSelected" @day-click="click"@event-created="eventCreated" :config="config"></full-calendar>

</template>

Body:
If using the vanilla FullCalendar via npm packages: "@fullcalendar/core", "@fullcalendar/daygrid", "@fullcalendar/timegrid", "@fullcalendar/vue"

html: <full-calendar ref="fullCalendar" :events="events" />
inside a method to update an event:
        let calendar = this.$refs.fullCalendar.getApi()
        const updatedEvent = calendar.getEventById(eventId)
        updatedEvent.setProp('title', 'New Title')
        updatedEvent.setProp('backgroundColor', 'yellow')
        updatedEvent.setProp('borderColor', 'yellow')
        updatedEvent.setProp('textColor', 'black')

The above will rerender the fullCalendar event but will not change your this.events array. There may be something that's a bit more all inclusive for ALL events in one shot otherwise you'd have to do:

this.events.forEach(event => {
  ...similar code the above
})


问:
Multiple Generic Types
So first of all, I will specify that my question is not referring to having multiple generics being applied to a class. I know you can do that simply with a comma.

My question is if there is a way to have multiple possible extensions for a generics. For example:

```<code>public class Foo<? extends String>{}
public class Bar<? extends StringBuilder>{}
//combined
public class FooBar<? extends String, StringBuilder>{}
//or perhaps
public class FooBar<? extends String || StringBuilder>{}
</code>```

I know the FooBar class will not compile but I hope that is helpful in explaining my question and the specified intent. To lastly reiterate my question: is it possible for two classes to be extended in the generic clause or a way that would simulate such an action indirectly?

Note I am not asking how generics work, nor how extensions work, nor anything involving how and when to use of generics, for I already know this. If the question needs clarification, I will edit to provide further understanding to the best of my abilities.

答:
So what you are asking isn't possible out of the box as John has said, but you can still achieve similar behavior using so called Either type which is used to represent situation where you can either 1 of 2 types.

You can easily find fully implemented Either class with simple google search, for example this one on github

For code snippet bellow lets consider this simplified version:

```<code>public class Either<L, R> {
    private final L left;
    private final R right;
    private final boolean isRight;

    private Either(L left, R right, boolean isRight) {
        this.left = left;
        this.right = right;
        this.isRight = isRight;
    }

    public static <L, R> Either<L, R> left(L left){
        return new Either<>(left, null, false);
    }

    public static <L, R> Either<L, R> right(R right){
        return new Either<>(null, right, true);
    }

    public <T>  T fold(Function<L,T> foldLeft, Function<R, T> foldRight){
        return isRight ? foldRight.apply(right) : foldLeft.apply(left);
    }
}
</code>```

Now lets say you have interface with some method that should accept String or StringBuilder:

```<code>public interface IFooBar <T extends Either<? extends String, ? extends StringBuilder>>{
    String  doSomething(T t);
}
</code>```

And implementation:

```<code>class FooBar implements IFooBar<Either<String, StringBuilder>> {
    @Override
    public String doSomething(Either<String, StringBuilder> either) {
        return either.fold(s -> "String: " + s, sb -> "StringBuilder:" + sb);
    }
}
</code>```

Then you can simply use it like this:

```<code>public static void main(String[] args) {
    IFooBar<Either<String, StringBuilder>> fooBar = new FooBar();
    // Since in this case it is single method interface you can even use lambda expression
    // IFooBar<Either<String, StringBuilder>> fooBar = either -> either.fold(s -> "String: " + s, sb -> "StringBuilder:" + sb);
    System.out.println(fooBar.doSomething(Either.left("Foo")));
    System.out.println(fooBar.doSomething(Either.right(new StringBuilder("Bar"))));
}
</code>```

I hope that this helps you.

Title: Multiple Generic Types

Body:
So first of all, I will specify that my question is not referring to having multiple generics being applied to a class. I know you can do that simply with a comma.

My question is if there is a way to have multiple possible extensions for a generics. For example:

public class Foo<? extends String>{}
public class Bar<? extends StringBuilder>{}
//combined
public class FooBar<? extends String, StringBuilder>{}
//or perhaps
public class FooBar<? extends String || StringBuilder>{}

I know the FooBar class will not compile but I hope that is helpful in explaining my question and the specified intent. To lastly reiterate my question: is it possible for two classes to be extended in the generic clause or a way that would simulate such an action indirectly?

Note I am not asking how generics work, nor how extensions work, nor anything involving how and when to use of generics, for I already know this. If the question needs clarification, I will edit to provide further understanding to the best of my abilities.

Body:
So what you are asking isn't possible out of the box as John has said, but you can still achieve similar behavior using so called Either type which is used to represent situation where you can either 1 of 2 types.

You can easily find fully implemented Either class with simple google search, for example this one on github

For code snippet bellow lets consider this simplified version:

public class Either<L, R> {
    private final L left;
    private final R right;
    private final boolean isRight;

    private Either(L left, R right, boolean isRight) {
        this.left = left;
        this.right = right;
        this.isRight = isRight;
    }

    public static <L, R> Either<L, R> left(L left){
        return new Either<>(left, null, false);
    }

    public static <L, R> Either<L, R> right(R right){
        return new Either<>(null, right, true);
    }

    public <T>  T fold(Function<L,T> foldLeft, Function<R, T> foldRight){
        return isRight ? foldRight.apply(right) : foldLeft.apply(left);
    }
}

Now lets say you have interface with some method that should accept String or StringBuilder:

public interface IFooBar <T extends Either<? extends String, ? extends StringBuilder>>{
    String  doSomething(T t);
}

And implementation:

class FooBar implements IFooBar<Either<String, StringBuilder>> {
    @Override
    public String doSomething(Either<String, StringBuilder> either) {
        return either.fold(s -> "String: " + s, sb -> "StringBuilder:" + sb);
    }
}

Then you can simply use it like this:

public static void main(String[] args) {
    IFooBar<Either<String, StringBuilder>> fooBar = new FooBar();
    // Since in this case it is single method interface you can even use lambda expression
    // IFooBar<Either<String, StringBuilder>> fooBar = either -> either.fold(s -> "String: " + s, sb -> "StringBuilder:" + sb);
    System.out.println(fooBar.doSomething(Either.left("Foo")));
    System.out.println(fooBar.doSomething(Either.right(new StringBuilder("Bar"))));
}

I hope that this helps you.


问:
Postman POST works properly; Ruby POST does not. How do I debug the difference?
I need to do a POST request for an API that takes a JSON payload that contains a nested stringified JSON object. I do a GET request to get the string, parse it (twice!) to get the hash, modify one parameter, then POST it back. When I post via Postman, it goes through as normal. When I post the same string via the Ruby Rest-Client gem, it seems that the POST goes through but there is an issue with how the payload is stringified, providing an unwanted result.

Unfortunately, I cannot refactor this admittedly poorly-designed back end. I can only work with what I have.

I have tried a dozen permutations of this code. Everything going into the post looks correct and identical to the Postman post.

Here is the Postman HTTP-ified, stripped of identifying information:

```<code>POST /example/home/api/savesettings HTTP/1.1
Host: dev.noneofyourbusiness.com
Cookie: identification-gui=f4k3-gu1-5tr1n9
Content-Type: application/json

{"settings":"{\"rows\":50,\"columns\":[\"Col1\",\"Col2\",\"Col3\",\"Col4\"],\"sort\":{\"column\":\"Col1\",\"direction\":1},\"filters\":{\"Status\":[\"Active\"]},\"widths\":{\"Id\":\"170px\",\"Description\":\"192px\"}}"}
</code>```

Here is the Ruby code, meant to do the same thing:

response = RestClient.get(
        get_url,
        :accept => :json,
        :cookies => {cookie[:name] => cookie[:value]}
    )

hash = JSON.parse(JSON.parse(response))
hash['columns'] = "Col1;Col2;Col3;Col4"
payload = {:settings => hash.to_json}.to_json

RestClient.post(
        post_url,
        payload,
        :content_type => :json,
        :cookies => {cookie[:name] => cookie[:value]}
    )
```

The Postman request sets the columns correctly. The Ruby request seems to wipe all of the settings, leading me to believe that the JSON is not formatted correctly, but I'm not sure.

When debugging, the Postman body/Rest-Client payload look identical.

答:
After a week of slamming my head against the desk, I realized that all I needed to do is add

```<code>.split(";")
</code>```

to the end of my columns. Everything works now.

Body:
I need to do a POST request for an API that takes a JSON payload that contains a nested stringified JSON object. I do a GET request to get the string, parse it (twice!) to get the hash, modify one parameter, then POST it back. When I post via Postman, it goes through as normal. When I post the same string via the Ruby Rest-Client gem, it seems that the POST goes through but there is an issue with how the payload is stringified, providing an unwanted result.

Unfortunately, I cannot refactor this admittedly poorly-designed back end. I can only work with what I have.

I have tried a dozen permutations of this code. Everything going into the post looks correct and identical to the Postman post.

Here is the Postman HTTP-ified, stripped of identifying information:

POST /example/home/api/savesettings HTTP/1.1
Host: dev.noneofyourbusiness.com
Cookie: identification-gui=f4k3-gu1-5tr1n9
Content-Type: application/json

{"settings":"{\"rows\":50,\"columns\":[\"Col1\",\"Col2\",\"Col3\",\"Col4\"],\"sort\":{\"column\":\"Col1\",\"direction\":1},\"filters\":{\"Status\":[\"Active\"]},\"widths\":{\"Id\":\"170px\",\"Description\":\"192px\"}}"}

Here is the Ruby code, meant to do the same thing:

response = RestClient.get(
        get_url,
        :accept => :json,
        :cookies => {cookie[:name] => cookie[:value]}
    )

hash = JSON.parse(JSON.parse(response))
hash['columns'] = "Col1;Col2;Col3;Col4"
payload = {:settings => hash.to_json}.to_json

RestClient.post(
        post_url,
        payload,
        :content_type => :json,
        :cookies => {cookie[:name] => cookie[:value]}
    )

The Postman request sets the columns correctly. The Ruby request seems to wipe all of the settings, leading me to believe that the JSON is not formatted correctly, but I'm not sure.

When debugging, the Postman body/Rest-Client payload look identical.

Body:
After a week of slamming my head against the desk, I realized that all I needed to do is add

.split(";")

to the end of my columns. Everything works now.


问:
Why am I in an endless loop when using LIKE in Access VBA query
I am using openrecordset to do a select query but I want the query to look for a specific word within a column and only return those records.

I tried different styles and it seems I keep getting the same type of error:
runtime error 6: overflow. that is because of a counter that I have, which an integer can only hold no more that 32,000 bytes.

If I remove the counter, It because an endless loop, no error messages just stuff running in the background. I have to restart access.

```<code>'Variables
Dim counter As Integer

'DB variables
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb

'Get records query
Set rs = db.OpenRecordset("SELECT * FROM Price_List WHERE Description LIKE '*cabin*'")

'Determine if the specified valve for this project was found
If rs.EOF Then
    MsgBox "No records were found for enclosures." & vbNewLine & vbNewLine & _
    "You can contact someone", vbInformation + vbOKOnly, "No Records Found"
    End
End If

List10.RowSource = ""

'display
List10.ColumnCount = 5
List10.ColumnWidths = "1500;4000;1200;1200;1200" 'Setting column widths for each record

counter = 0
Do
    If counter = 0 Then
        List10.AddItem ("Part Number)
        List10.AddItem (rs!PartNumber)
    Else
        List10.AddItem (rs!PartNumber)
    End If

    'counter = counter + 1
Loop Until rs.EOF

Label14.Caption = rs.RecordCount

rs.Close
db.Close
</code>```

I expect it to return at least 5 records but I guess it's returning way more!

答:
After you checked for rs.EOF, you need to put the cursor on the first record and add to your list the title "Part Number" so you don't need if inside the loop.

After that start the loop and at the end of each iteration move to the next record:

```<code>rs.MoveFirst
List10.AddItem ("Part Number")
Do
    List10.AddItem (rs!PartNumber)
    counter = counter + 1
    rs.MoveNext
Loop Until rs.EOF
</code>```

Body:
I am using openrecordset to do a select query but I want the query to look for a specific word within a column and only return those records.

I tried different styles and it seems I keep getting the same type of error:
runtime error 6: overflow. that is because of a counter that I have, which an integer can only hold no more that 32,000 bytes.

If I remove the counter, It because an endless loop, no error messages just stuff running in the background. I have to restart access.

'Variables
Dim counter As Integer

'DB variables
Dim db As DAO.Database
Dim rs As DAO.Recordset
Set db = CurrentDb

'Get records query
Set rs = db.OpenRecordset("SELECT * FROM Price_List WHERE Description LIKE '*cabin*'")

'Determine if the specified valve for this project was found
If rs.EOF Then
    MsgBox "No records were found for enclosures." & vbNewLine & vbNewLine & _
    "You can contact someone", vbInformation + vbOKOnly, "No Records Found"
    End
End If

List10.RowSource = ""

'display
List10.ColumnCount = 5
List10.ColumnWidths = "1500;4000;1200;1200;1200" 'Setting column widths for each record

counter = 0
Do
    If counter = 0 Then
        List10.AddItem ("Part Number)
        List10.AddItem (rs!PartNumber)
    Else
        List10.AddItem (rs!PartNumber)
    End If

    'counter = counter + 1
Loop Until rs.EOF

Label14.Caption = rs.RecordCount

rs.Close
db.Close

I expect it to return at least 5 records but I guess it's returning way more!

Body:
After you checked for rs.EOF, you need to put the cursor on the first record and add to your list the title "Part Number" so you don't need if inside the loop.

After that start the loop and at the end of each iteration move to the next record:

rs.MoveFirst
List10.AddItem ("Part Number")
Do
    List10.AddItem (rs!PartNumber)
    counter = counter + 1
    rs.MoveNext
Loop Until rs.EOF


问:
Difference between events and delegates and its respective applications
I don't see advantages of using events over delegates, other than being syntactical sugar. Perhaps I am misunderstanding, but it seems that event is just a placeholder for delegate.

Would you explain to me the differences and when to use which?  What are the advantages and disadvantages? Our code is heavily rooted with events, and I want to get to the bottom of it.

When would you use delegates over events and vice versa? Please state your real world experience with both, say in the production code.

答:
The keyword event is a scope modifier for multicast delegates. Practical differences between this and just declaring a multicast delegate are as follows:

You can use event in an interface.

Invocation access to the multicast delegate is limited to the declaring class. The behaviour is as though the delegate were private for invocation. For the purposes of assignment, access is as specified by an explicit access modifier (eg public event).

As a matter of interest, you can apply + and - to multicast delegates, and this is the basis of the += and -= syntax for the combination assignment of delegates to events. These three snippets are equivalent:

```<code>B = new EventHandler(this.MethodB);
C = new EventHandler(this.MethodC);
A = B + C;
</code>```

Sample two, illustrating both direct assignment and combination assignment.

```<code>B = new EventHandler(this.MethodB);
C = new EventHandler(this.MethodC);
A = B;
A += C;
</code>```

Sample three: more familiar syntax. You are probably acquainted with the assignment of null to remove all handlers.

```<code>B = new EventHandler(this.MethodB);
C = new EventHandler(this.MethodC);
A = null;
A += B;
A += C;
</code>```

Like properties, events have a full syntax that no-one ever uses. This:

```<code>class myExample
{
  internal EventHandler eh;

  public event EventHandler OnSubmit
  {
    add
    {
      eh = Delegate.Combine(eh, value) as EventHandler;
    }
    remove
    {
      eh = Delegate.Remove(eh, value) as EventHandler;
    }
  }

  ...
}
</code>```

...does exactly the same as this:

```<code>class myExample
{
  public event EventHandler OnSubmit;
}
</code>```

The add and remove methods are more conspicuous in the rather stilted syntax that VB.NET uses (no operator overloads).

OwnerDisplayName: Sasha

LastEditorDisplayName: RoBorg

Body:
The keyword event is a scope modifier for multicast delegates. Practical differences between this and just declaring a multicast delegate are as follows:

You can use event in an interface.

Invocation access to the multicast delegate is limited to the declaring class. The behaviour is as though the delegate were private for invocation. For the purposes of assignment, access is as specified by an explicit access modifier (eg public event).

As a matter of interest, you can apply + and - to multicast delegates, and this is the basis of the += and -= syntax for the combination assignment of delegates to events. These three snippets are equivalent:

B = new EventHandler(this.MethodB);
C = new EventHandler(this.MethodC);
A = B + C;

Sample two, illustrating both direct assignment and combination assignment.

B = new EventHandler(this.MethodB);
C = new EventHandler(this.MethodC);
A = B;
A += C;

Sample three: more familiar syntax. You are probably acquainted with the assignment of null to remove all handlers.

B = new EventHandler(this.MethodB);
C = new EventHandler(this.MethodC);
A = null;
A += B;
A += C;

Like properties, events have a full syntax that no-one ever uses. This:

class myExample
{
  internal EventHandler eh;

  public event EventHandler OnSubmit
  {
    add
    {
      eh = Delegate.Combine(eh, value) as EventHandler;
    }
    remove
    {
      eh = Delegate.Remove(eh, value) as EventHandler;
    }
  }

  ...
}

...does exactly the same as this:

class myExample
{
  public event EventHandler OnSubmit;
}

The add and remove methods are more conspicuous in the rather stilted syntax that VB.NET uses (no operator overloads).

OwnerDisplayName: Peter Wone


问:
How to setState to answer from APi
Im trying to setState to response from Api onClick. Status got update but not when im clicking for first time, with second click, yes it does update.

```<code>     fetch(URL)
          .then(res => res.json())
          .then(res => {
            this.setState({
              recipesList: res
            });
          });
    console.log(this.state.recipesList);

  };
</code>```

Can someone help me ?

答:
You did not provide full code but from this piece I see that console.log(this.state.recipesList); is outside of promise chain.

Because fetch() is asynchronous than console.log(this.state.recipesList); will be executed before

this.setState({
  recipesList: res
});

Put your console.log() into callback of this.setState() which will be executed after state update.

```<code>fetch(URL)
 .then(res => res.json())
 .then(res => {
    this.setState({
      recipesList: res
    }, () => {
      console.log(this.state.recipesList);
    });
 });
</code>```

Title: How to setState to answer from APi

Body:
Im trying to setState to response from Api onClick. Status got update but not when im clicking for first time, with second click, yes it does update.

     fetch(URL)
          .then(res => res.json())
          .then(res => {
            this.setState({
              recipesList: res
            });
          });
    console.log(this.state.recipesList);

  };

Can someone help me ?

Body:
You did not provide full code but from this piece I see that console.log(this.state.recipesList); is outside of promise chain.

Because fetch() is asynchronous than console.log(this.state.recipesList); will be executed before

this.setState({
  recipesList: res
});

Put your console.log() into callback of this.setState() which will be executed after state update.

fetch(URL)
 .then(res => res.json())
 .then(res => {
    this.setState({
      recipesList: res
    }, () => {
      console.log(this.state.recipesList);
    });
 });


问:
How to set up multiple crons for different timezones
Following my question about cron job and timezone

I would like to know what would be the best way to  schedule things at different time zones:

Something to run at : 16h30 Tokyo time

Then another to run at :  10AM London time

Another at 3PM NYC Time , etc etc.

I have multiple cron jobs like those that i need to run and my code from previous post doesn't seem to cut it.

I don't know what is the best way to proceed as it should be independent of the server time, so working with UTC time doesn't really cut it.

```<code>package main

import (
    "fmt"
    "github.com/robfig/cron"
    "os"
    "os/signal"
    "time"
)

func helloWorld() {
  fmt.Println("hello world")
}

func main() {
    s, err1 := cron.Parse("30 10 * * *")
    fmt.Println(err1)
    l, err := time.LoadLocation("Asia/Tokyo")
    fmt.Println(err)
    c := cron.NewWithLocation(l)
    c.Schedule(s, cron.FuncJob(helloWorld))
    c.Start()

    sig := make(chan os.Signal)
    signal.Notify(sig, os.Interrupt, os.Kill)
    <-sig
}
</code>```

After my previous post i've found that you could check the scheduler this way :

```<code>    test := c.Entries()
    log.Println(test[0].Schedule)
    log.Println(test[0].Next)
    log.Println(test[0].Prev)
</code>```

and got as result (the first 2 nils being the err "handling"):

```<code>    <nil>
    <nil>
    2019/05/30 00:59:21 &{1073741824 1024 9223372036871553023 9223372041149743102 9223372036854783998 9223372036854775935}
    2019/05/30 00:59:21 2019-05-30 01:10:30 +0900 JST
    2019/05/30 00:59:21 0001-01-01 00:00:00 +0000 UTC
</code>```

You can see that it's scheduled to run at 01:10:30 Japan time ( JST ) instead of 10:30 AM JST that i expected.

Anybody know what's happening. I'm gonna need to do this for upward of 70 timezones..

答:
As stated in the docs s, err1 := cron.Parse("30 10 * * *") creates a new cron job executed hourly at exactly 10mins and 30sec.

Because your time was 2019/05/30 00:59:21 the next avaiable slot would be exactly like stated 01:10:30 +0900 JST.

To create a new job executed daily at 10:30 local time use s, err1 := cron.Parse("0 30 10 * *") instead. For a quick overview use Predefined schedules in the docs, it displays it in a nice table.

Body:
Following my question about cron job and timezone

I would like to know what would be the best way to  schedule things at different time zones:

Something to run at : 16h30 Tokyo time

Then another to run at :  10AM London time

Another at 3PM NYC Time , etc etc.

I have multiple cron jobs like those that i need to run and my code from previous post doesn't seem to cut it.

I don't know what is the best way to proceed as it should be independent of the server time, so working with UTC time doesn't really cut it.

package main

import (
    "fmt"
    "github.com/robfig/cron"
    "os"
    "os/signal"
    "time"
)

func helloWorld() {
  fmt.Println("hello world")
}

func main() {
    s, err1 := cron.Parse("30 10 * * *")
    fmt.Println(err1)
    l, err := time.LoadLocation("Asia/Tokyo")
    fmt.Println(err)
    c := cron.NewWithLocation(l)
    c.Schedule(s, cron.FuncJob(helloWorld))
    c.Start()

    sig := make(chan os.Signal)
    signal.Notify(sig, os.Interrupt, os.Kill)
    <-sig
}

After my previous post i've found that you could check the scheduler this way :

    test := c.Entries()
    log.Println(test[0].Schedule)
    log.Println(test[0].Next)
    log.Println(test[0].Prev)

and got as result (the first 2 nils being the err "handling"):

    <nil>
    <nil>
    2019/05/30 00:59:21 &{1073741824 1024 9223372036871553023 9223372041149743102 9223372036854783998 9223372036854775935}
    2019/05/30 00:59:21 2019-05-30 01:10:30 +0900 JST
    2019/05/30 00:59:21 0001-01-01 00:00:00 +0000 UTC

You can see that it's scheduled to run at 01:10:30 Japan time ( JST ) instead of 10:30 AM JST that i expected.

Anybody know what's happening. I'm gonna need to do this for upward of 70 timezones..


问:
How can i remove " sdl2 - ImportError" and "pil - ModuleNotFoundError" from my kivy program
I am new to kivy , want to run my very first program but i am getting

```<code>sdl2 - ImportError: DLL load failed " and "pil - ModuleNotFoundError: No module named 'PIL'
</code>```

what should i do to eliminate the error?

i tried  installing all:

```<code>python -m pip install docutils pygments pypiwin32 kivy.deps.sdl2 kivy.deps.glew

python -m pip install kivy.deps.sdl2
</code>```

but nothing seems to resolve my issue.

this is my code i tried:

import kivy
from kivy.app import App
from kivy.uix.label import Label

class Myapp(App):
    def  build(self):
        return Label(text="Abhay 's APP")

if __name__ == "__main__":
    Myapp().run()
```

<p>OUTPUT I Got:</p>

```[INFO   ] [Logger      ] Record log in C:\Users\SONY VAIO\.kivy\logs\kivy_19-05-05_44.txt
[INFO   ] [Kivy        ] v1.10.1
[INFO   ] [Python      ] v3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 22:20:52) [MSC v.1916 32 bit (Intel)]
[INFO   ] [Factory     ] 194 symbols loaded
[INFO   ] [Image       ] Providers: img_tex, img_dds, img_gif (img_sdl2, img_pil, img_ffpyplayer ignored)
[CRITICAL] [Text        ] Unable to find any valuable Text provider.
sdl2 - ImportError: DLL load failed: The specified module could not be found.
  File "C:\Users\SONY VAIO\AppData\Local\Programs\Python\Python37-32\lib\site-packages\kivy\core\__init__.py", line 59, in core_select_lib
    fromlist=[modulename], level=0)
  File "C:\Users\SONY VAIO\AppData\Local\Programs\Python\Python37-32\lib\site-packages\kivy\core\text\text_sdl2.py", line 12, in <module>
    from kivy.core.text._text_sdl2 import (_SurfaceContainer, _get_extents,

pil - ModuleNotFoundError: No module named 'PIL'
  File "C:\Users\SONY VAIO\AppData\Local\Programs\Python\Python37-32\lib\site-packages\kivy\core\__init__.py", line 59, in core_select_lib
    fromlist=[modulename], level=0)
  File "C:\Users\SONY VAIO\AppData\Local\Programs\Python\Python37-32\lib\site-packages\kivy\core\text\text_pil.py", line 7, in <module>
    from PIL import Image, ImageFont, ImageDraw

[CRITICAL] [App         ] Unable to get a Text provider, abort.
```

答:
Had the same problem. Apparently there's no Python 3.5+ support with pypi.

Instead, try installing it from the master branch on github:

```<code>python -m pip install https://github.com/kivy/kivy/archive/master.zip
</code>```

Make sure to install pygame as well:

```<code>python -m pip install pygame
</code>```

Found this solution on their github:
https://github.com/kivy/kivy/issues/4991

Body:
I am new to kivy , want to run my very first program but i am getting

sdl2 - ImportError: DLL load failed " and "pil - ModuleNotFoundError: No module named 'PIL'

what should i do to eliminate the error?

i tried  installing all:

python -m pip install docutils pygments pypiwin32 kivy.deps.sdl2 kivy.deps.glew

python -m pip install kivy.deps.sdl2

but nothing seems to resolve my issue.

this is my code i tried:

import kivy
from kivy.app import App
from kivy.uix.label import Label

class Myapp(App):
    def  build(self):
        return Label(text="Abhay 's APP")

if __name__ == "__main__":
    Myapp().run()

OUTPUT I Got:

[INFO   ] [Logger      ] Record log in C:\Users\SONY VAIO\.kivy\logs\kivy_19-05-05_44.txt
[INFO   ] [Kivy        ] v1.10.1
[INFO   ] [Python      ] v3.7.2 (tags/v3.7.2:9a3ffc0492, Dec 23 2018, 22:20:52) [MSC v.1916 32 bit (Intel)]
[INFO   ] [Factory     ] 194 symbols loaded
[INFO   ] [Image       ] Providers: img_tex, img_dds, img_gif (img_sdl2, img_pil, img_ffpyplayer ignored)
[CRITICAL] [Text        ] Unable to find any valuable Text provider.
sdl2 - ImportError: DLL load failed: The specified module could not be found.
  File "C:\Users\SONY VAIO\AppData\Local\Programs\Python\Python37-32\lib\site-packages\kivy\core\__init__.py", line 59, in core_select_lib
    fromlist=[modulename], level=0)
  File "C:\Users\SONY VAIO\AppData\Local\Programs\Python\Python37-32\lib\site-packages\kivy\core\text\text_sdl2.py", line 12, in <module>
    from kivy.core.text._text_sdl2 import (_SurfaceContainer, _get_extents,

pil - ModuleNotFoundError: No module named 'PIL'
  File "C:\Users\SONY VAIO\AppData\Local\Programs\Python\Python37-32\lib\site-packages\kivy\core\__init__.py", line 59, in core_select_lib
    fromlist=[modulename], level=0)
  File "C:\Users\SONY VAIO\AppData\Local\Programs\Python\Python37-32\lib\site-packages\kivy\core\text\text_pil.py", line 7, in <module>
    from PIL import Image, ImageFont, ImageDraw

[CRITICAL] [App         ] Unable to get a Text provider, abort.

Body:
Had the same problem. Apparently there's no Python 3.5+ support with pypi.

Instead, try installing it from the master branch on github:

python -m pip install https://github.com/kivy/kivy/archive/master.zip

Make sure to install pygame as well:

python -m pip install pygame

Found this solution on their github:
https://github.com/kivy/kivy/issues/4991


问:
Question about <form onsubmit "function() ">
i have wrote a function to activate onsubmit"" in the form.
In the function(JavaScript) i try to fill variables with input from the fieldset.
On troubleshooting i immediately found out that all the input gets cleared before i can save them into the variables.
I know that this is not how forms are used but i do like how it points out the fields that still needs to be filled.
so is there a way or someone how figured out a way to outsmart the submit to do something(function) before the refresh? or is there absolutely no way?

```<code>function objectfill() {
var vnaam = document.getElementById('Voornaam').value;
var anaam = document.getElementById('naam').value;
var mail = document.getElementById('email').value;
var tele = document.getElementById('mobiel').value;
var rknr = document.getElementById('rijksregister').value;
var actie = document.getElementById('workshop').value
var k = document.getElementsByName('Room');
var room
for (var i = 0; i < k.length; i++) {
    if (k[i].checked) {
        room = k[i].value;
    }
}

var personeel = new personeelgegevens(pnr, vnaam, anaam, mail, tele, rknr,
actie, room);
console.log(personeel)
</code>```

This was the function i used onsubmit="objectfill()"
I wanted to fill the object but obviously not working.

答:
You just need to prevent that submit from happening so that your JavaScript can run, by calling event.preventDefault(). Also, try using element.addEventListener() instead of inline event properties.

```<code>// Assuming a form that looks like
<form id="myform">

// Do

const form = document.getElementById('form')

form.addEventListener('submit', event => {
  // prevent the form from submitting
  event.preventDefault()

  // The rest of your form code here
})
</code>```

Body:
i have wrote a function to activate onsubmit"" in the form.
In the function(JavaScript) i try to fill variables with input from the fieldset.
On troubleshooting i immediately found out that all the input gets cleared before i can save them into the variables.
I know that this is not how forms are used but i do like how it points out the fields that still needs to be filled.
so is there a way or someone how figured out a way to outsmart the submit to do something(function) before the refresh? or is there absolutely no way?

function objectfill() {
var vnaam = document.getElementById('Voornaam').value;
var anaam = document.getElementById('naam').value;
var mail = document.getElementById('email').value;
var tele = document.getElementById('mobiel').value;
var rknr = document.getElementById('rijksregister').value;
var actie = document.getElementById('workshop').value
var k = document.getElementsByName('Room');
var room
for (var i = 0; i < k.length; i++) {
    if (k[i].checked) {
        room = k[i].value;
    }
}

var personeel = new personeelgegevens(pnr, vnaam, anaam, mail, tele, rknr,
actie, room);
console.log(personeel)

This was the function i used onsubmit="objectfill()"
I wanted to fill the object but obviously not working.

Body:
You just need to prevent that submit from happening so that your JavaScript can run, by calling event.preventDefault(). Also, try using element.addEventListener() instead of inline event properties.

// Assuming a form that looks like
<form id="myform">

// Do

const form = document.getElementById('form')

form.addEventListener('submit', event => {
  // prevent the form from submitting
  event.preventDefault()

  // The rest of your form code here
})


问:
Assign nil value to double in Objective-C
In my iOS iPhone app I have this method:

```<code>-(id)initWithLocationName:(NSString *)locatNm latitude:(double)lati longitude:(double)longi xCoord:(double)xco yCoord:(double)yco;
</code>```

In this method I need to assign nil value to xCoord & yCoord.

How can I assign nil to double?

答: You could use NSNumber.</p>

Body:
In my iOS iPhone app I have this method:

-(id)initWithLocationName:(NSString *)locatNm latitude:(double)lati longitude:(double)longi xCoord:(double)xco yCoord:(double)yco;

In this method I need to assign nil value to xCoord & yCoord.

How can I assign nil to double?

Body: You could use NSNumber.


问:
Create style that extends from default style set in application theme
I have set the default button style in my application theme, so that it is applied to every button in the app.

There are few buttons that need to have their text capitalized in addition to default style. So what I'm trying to do is something like this

(the following code snippet doesn't work as I cannot set parent="?attr/materialButtonStyle"):

```<code><style name="capitalizedButton" parent="?attr/materialButtonStyle">
    <item name="android:textAllCaps">true</item>
</style>
</code>```

Is it possible to extend a style defined in theme.xml? I don't want to refer to the local style that I'm setting in theme as that can change later, instead I intend to access it using theme attribute.

答:
You can directly pass style to Button widget in you XML like:

```<code><Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="capitalizedButton"/>
</code>```

Hope you get the answer. If not please explain your question.

Body:
I have set the default button style in my application theme, so that it is applied to every button in the app.

There are few buttons that need to have their text capitalized in addition to default style. So what I'm trying to do is something like this

(the following code snippet doesn't work as I cannot set parent="?attr/materialButtonStyle"):

Is it possible to extend a style defined in theme.xml? I don't want to refer to the local style that I'm setting in theme as that can change later, instead I intend to access it using theme attribute.

Body:
You can directly pass style to Button widget in you XML like:

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        style="capitalizedButton"/>

Hope you get the answer. If not please explain your question.


问:
Points in a rectangle All
I am trying to get all list of points to populate a boolean true if the list of points fall within a rectangle.

I've tried to run the below code in Jupyterlab. but I keep getting the following error:

TypeError: '>=' not supported between instances of 'tuple' and 'int'

```<code>def allIn(firstCorner=(0,0), secondCorner=(0,0), pointList=[]):
   fc1,sc1=firstCorner[0],firstCorner[1]
   fc2,sc2=secondCorner[0],secondCorner[1]

   fc,sc=pointList[0],pointList[1]
   if (fc >= fc1 and fc <= fc2 and sc >= sc1 and sc <= sc2) :
       return True
   elif(fc >= fc2 and fc <= fc1 and sc >= sc2 and sc <= sc1):
       return True
   else:
       return False

print(allIn((0,0), (5,5), [(1,1), (0,0), (5,5)]))
</code>```

I expect the output to be allIn((0,0), (5,5), [(1,1), (0,0), (5,5)]) should return True but allIn((0,0), (5,5), [(1,1), (0,0), (5,6)]) should return False
and empty list of points allIn((0,0), (5,5), []) should return False

答:
Your pointsList is a list of tuples. You have set

```<code>fc,sc=pointList[0],pointList[1]
</code>```

So fc and sc are tuples. When you do

```<code>if (fc >= fc1 and fc <= fc2 and sc >= sc1 and sc <= sc2) :
</code>```

You are comparing fc (a tuple) to fc1 (an int), which will throw a TypeError. To make the correct comparison look at pointList[0][0], pointList[0][1], pointList[1][0], etc.

Title: Points in a rectangle All

Body:
I am trying to get all list of points to populate a boolean true if the list of points fall within a rectangle.

I've tried to run the below code in Jupyterlab. but I keep getting the following error:

TypeError: '>=' not supported between instances of 'tuple' and 'int'

def allIn(firstCorner=(0,0), secondCorner=(0,0), pointList=[]):
   fc1,sc1=firstCorner[0],firstCorner[1]
   fc2,sc2=secondCorner[0],secondCorner[1]

   fc,sc=pointList[0],pointList[1]
   if (fc >= fc1 and fc <= fc2 and sc >= sc1 and sc <= sc2) :
       return True
   elif(fc >= fc2 and fc <= fc1 and sc >= sc2 and sc <= sc1):
       return True
   else:
       return False

print(allIn((0,0), (5,5), [(1,1), (0,0), (5,5)]))

I expect the output to be allIn((0,0), (5,5), [(1,1), (0,0), (5,5)]) should return True but allIn((0,0), (5,5), [(1,1), (0,0), (5,6)]) should return False
and empty list of points allIn((0,0), (5,5), []) should return False

Body:
Your pointsList is a list of tuples. You have set

fc,sc=pointList[0],pointList[1]

So fc and sc are tuples. When you do

if (fc >= fc1 and fc <= fc2 and sc >= sc1 and sc <= sc2) :

You are comparing fc (a tuple) to fc1 (an int), which will throw a TypeError. To make the correct comparison look at pointList[0][0], pointList[0][1], pointList[1][0], etc.


问:
Unlimited Offline Storage
Our project needs to store like 200Gb of images for offline usage!

I am making a PWA using Workbox and then setting its URL as the homepage parameter for “Chrome App Builder”

Then this Chrome App will be set to work in Kiosk mode.

The project requirements are that the whole kiosk with all its content should be able to work offline, which means it needs to store like 200Gb of images mostly.

From my research, it seems that it is not possible for a PWA to store more than 6% of available disk space (on chrome).
I am sure that is not enough for our use-case.

Although there is permission named unlimitedStorage for Chrome Apps, I am not sure if that's the way to go! Apparently, I am confusing concepts!

Any suggestions guys?

答:
Please see https://developers.google.com/web/updates/2016/06/persistent-storage for guidance around requesting persistent storage. This does not exempt you from the overall quota limitations, but it makes your origin's storage less likely to be auto-cleared when a device experiences low-space.

I'd strongly suggest looking into whether an alternative image format will end up allowing you to store the same number of images in less overall space. If you know that you're using are going to be on Chrome, for instance, then WebP will definitely be supported. Converting your images to WebP (or otherwise optimizing them) sounds like it would be an important step to take.

Title: Unlimited Offline Storage


问:
Relative z-index?
I've got a "Dialog" widget that pops up with a z-index of 100.  When I create another popup (a floating div), it appears underneath the dialog widget, because I haven't explicitly set the z-index on the new popup.

The structure ends up looking something like

```<code><div id="dialogbox" style="z-index: 100">
    <div>
        <div id="widgetThatCausesThePopup" />
    </div>
</div>
<div id="popupHiddenBehindTheDialog" />
</code>```

I'm using GWT to generate this HTML.  There can be arbitrary levels of nesting between dialogbox and widgetThatCausesThePopup, and the actual z-index may be arbitrary as well.

How can I ensure that the new div will be shown in front of the dialogbox?

答:
If your new dialog windows are inserted in the DOM after the previous ones:

You can set the z-index: 100 on all dialog windows.  When elements with the same z-index are found, order in the DOM determines which is on top.

Title: Relative z-index?

Body:
I've got a "Dialog" widget that pops up with a z-index of 100.  When I create another popup (a floating div), it appears underneath the dialog widget, because I haven't explicitly set the z-index on the new popup.

The structure ends up looking something like

I'm using GWT to generate this HTML.  There can be arbitrary levels of nesting between dialogbox and widgetThatCausesThePopup, and the actual z-index may be arbitrary as well.

How can I ensure that the new div will be shown in front of the dialogbox?


答:
setState() is asynchronous. This means that React will choose when is the right time to update the state, which is probably not when you are doing console.log().

Use console.log() on the setState callback, so when the state changes, your function is executed:

```<code>fetch(URL)
   .then(res => res.json())
   .then(res => {
       this.setState({
          recipesList: res
       },()=>{//setState callback.
          console.log(this.state.recipesList);
       });
    });
</code>```

Use the fetch function in componentWillMount()

This is due to ReactJS lifecycle. If you execute the function inside componentWillMount it won't cause a second render:

```<code>class yourComponent extends React.Component{

  state = {
     recipesList: []
  }

  componentWillMount(){
    fetch(URL)
     .then(res => res.json())
     .then(res => {
         this.setState({
            recipesList: res
         },()=>{//setState callback.
            console.log(this.state.recipesList);
         });
      });
   }
}
</code>```

EDIT:

If you used fetch inside componentWillMount(), you can:

Render from map directly to render.

In your render method, use the map function like this:

```<code>render(){
    return (
      <div className="App">
        <div className="contentWrapper">
          {
             this.state.recipesList.map(item => {
               return (
                  <div className="recispesList">
                     <h1>{item.title}</h1>
                  </div>
               );
             })
          }
        </div>
      </div>
    );
}
</code>```

Title: How to setState to answer from APi

Body:
setState() is asynchronous. This means that React will choose when is the right time to update the state, which is probably not when you are doing console.log().

Use console.log() on the setState callback, so when the state changes, your function is executed:

fetch(URL)
   .then(res => res.json())
   .then(res => {
       this.setState({
          recipesList: res
       },()=>{//setState callback.
          console.log(this.state.recipesList);
       });
    });

Use the fetch function in componentWillMount()

This is due to ReactJS lifecycle. If you execute the function inside componentWillMount it won't cause a second render:

class yourComponent extends React.Component{

  state = {
     recipesList: []
  }

  componentWillMount(){
    fetch(URL)
     .then(res => res.json())
     .then(res => {
         this.setState({
            recipesList: res
         },()=>{//setState callback.
            console.log(this.state.recipesList);
         });
      });
   }
}

EDIT:

If you used fetch inside componentWillMount(), you can:

Render from map directly to render.

In your render method, use the map function like this:

render(){
    return (
      <div className="App">
        <div className="contentWrapper">
          {
             this.state.recipesList.map(item => {
               return (
                  <div className="recispesList">
                     <h1>{item.title}</h1>
                  </div>
               );
             })
          }
        </div>
      </div>
    );
}