问:
Node/Express - Refused to apply style because its MIME type ('text/html')
I've been having this issue for the past couple of days and can't seem to get to the bottom of this. We doing a very basic node/express app, and are trying to serve our static files using something like this:

```<code>app.use(express.static(path.join(__dirname, "static")));
</code>```

This does what I expect it to for the most part. We have a few folders in our static folder for our css and javascript. We're trying to load our css into our EJS view using this static path:

```<code><link rel="stylesheet" type="text/css" href="/css/style.css">
</code>```

When we hit our route /, we're getting all of the content but our CSS is not loading. We're getting this error in particular:

Refused to apply style from 'http://localhost:3000/css/style.css'
  because its MIME type ('text/html') is not a supported stylesheet MIME
  type, and strict MIME checking is enabled.

What I've tried:

Clear NPM Cache / Fresh Install

npm verify cache

rm -rf node_modules

npm install

Clear Browser Cache

Various modifications to folder names and references to that

Adding/removing forward slashes form the href

Moving the css folder into the root and serving it from there

Adding/removing slashes from path.join(__dirname, '/static/')

There was a comment about a service worker possibly messing things up in a github issue report, and seemed to fix a lot of people's problems. There is no service worker for our localhost: https://github.com/facebook/create-react-app/issues/658

We're not using react, but I'm grasping at any google search I can find

The route:

```<code>app.get("/", function(req, res) {
    res.render("search");
});
</code>```

The view:

```<code><!DOCTYPE html>
<html>
    <head>
        <title>Search for a Movie</title>
        <link rel="stylesheet" type="text/css" href="/static/css/style.css">
    </head>
    <body>
        <h1>Search for a movie</h1>
        <form method="POST" action="/results">
            <label for="movie-title">Enter a movie title:</label><br>
            <input id="movie-title" type="text" name="title"><br>
            <input type="submit" value="Submit Search">
        </form>
    </body>
</html>
</code>```

The package.json:

```<code>{
  "name": "express-apis-omdb",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "start": "nodemon index.js",
    "lint:js": "node_modules/eslint/bin/eslint.js ./ ./**/*.js --fix; exit 0",
    "lint:css": "node_modules/csslint/cli.js public/css/; exit 0"
  },
  "license": "ISC",
  "devDependencies": {
    "babel-eslint": "^6.0.4",
    "csslint": "^0.10.0",
    "eslint": "^2.11.1",
    "eslint-config-airbnb": "^9.0.1",
    "eslint-plugin-import": "^1.8.1",
    "eslint-plugin-jsx-a11y": "^1.3.0",
    "eslint-plugin-react": "^5.1.1"
  },
  "dependencies": {
    "body-parser": "^1.18.2",
    "dotenv": "^5.0.0",
    "ejs": "^2.5.7",
    "express": "^4.13.4",
    "morgan": "^1.7.0",
    "path": "^0.12.7",
    "request": "^2.83.0"
  }
}
</code>```

The project structure:

```<code>-app
--node_modules
--static
---img
---css
---js
--views
---movie.ejs
---results.ejs
---search.ejs
--index.js
--package-lock.json
--package.json
</code>```

Note: We are currently not using a layout file for our EJS.

I'm happy to provide additional details if needed.

答:
In Nodejs app with express, we need to add the line like below to tell the server about the directory

app.use(express.static(__dirname));
```

This will solve the problem of CSS not rendering

Body:
I've been having this issue for the past couple of days and can't seem to get to the bottom of this. We doing a very basic node/express app, and are trying to serve our static files using something like this:

app.use(express.static(path.join(__dirname, "static")));

This does what I expect it to for the most part. We have a few folders in our static folder for our css and javascript. We're trying to load our css into our EJS view using this static path:

<link rel="stylesheet" type="text/css" href="/css/style.css">

When we hit our route /, we're getting all of the content but our CSS is not loading. We're getting this error in particular:

Refused to apply style from 'http://localhost:3000/css/style.css'
  because its MIME type ('text/html') is not a supported stylesheet MIME
  type, and strict MIME checking is enabled.

What I've tried:

Clear NPM Cache / Fresh Install

npm verify cache

rm -rf node_modules

npm install

Clear Browser Cache

Various modifications to folder names and references to that

Adding/removing forward slashes form the href

Moving the css folder into the root and serving it from there

Adding/removing slashes from path.join(__dirname, '/static/')

There was a comment about a service worker possibly messing things up in a github issue report, and seemed to fix a lot of people's problems. There is no service worker for our localhost: https://github.com/facebook/create-react-app/issues/658

We're not using react, but I'm grasping at any google search I can find

The route:

app.get("/", function(req, res) {
    res.render("search");
});

The view:

<!DOCTYPE html>

        <title>Search for a Movie</title>
        <link rel="stylesheet" type="text/css" href="/static/css/style.css">

Search for a movie

        <form method="POST" action="/results">
            Enter a movie title:

            <input id="movie-title" type="text" name="title">

            <input type="submit" value="Submit Search">
        </form>

The package.json:

{
  "name": "express-apis-omdb",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "start": "nodemon index.js",
    "lint:js": "node_modules/eslint/bin/eslint.js ./ ./**/*.js --fix; exit 0",
    "lint:css": "node_modules/csslint/cli.js public/css/; exit 0"
  },
  "license": "ISC",
  "devDependencies": {
    "babel-eslint": "^6.0.4",
    "csslint": "^0.10.0",
    "eslint": "^2.11.1",
    "eslint-config-airbnb": "^9.0.1",
    "eslint-plugin-import": "^1.8.1",
    "eslint-plugin-jsx-a11y": "^1.3.0",
    "eslint-plugin-react": "^5.1.1"
  },
  "dependencies": {
    "body-parser": "^1.18.2",
    "dotenv": "^5.0.0",
    "ejs": "^2.5.7",
    "express": "^4.13.4",
    "morgan": "^1.7.0",
    "path": "^0.12.7",
    "request": "^2.83.0"
  }
}

The project structure:

-app
--node_modules
--static
---img
---css
---js
--views
---movie.ejs
---results.ejs
---search.ejs
--index.js
--package-lock.json
--package.json

Note: We are currently not using a layout file for our EJS.

I'm happy to provide additional details if needed.

Body:
In Nodejs app with express, we need to add the line like below to tell the server about the directory

app.use(express.static(__dirname));

This will solve the problem of CSS not rendering


来源: stackexchange

问:
Add AAD Group to SQL Azure using Azure Devops Pipeline
I want to add an AD-Group to SQL Azure using Azure Devops. The AD group contains MSI of a webapp.

We've added a group to the AAD called DemoSqlAdmin, containing the SPN used in the Azure DevOps pipeline. This group has been set as the SQL Server - Active Directory admin.

When running the Azure Devops Task: Azure SQL Database Deployment with Authentication Type 'Active Directory - Integrated' we get the following error:

```<code>2019-05-08T17:44:56.3763560Z ##[debug]Run-InlineSql -authenticationType aadAuthenticationIntegrated -serverName demoserver.database.windows.net -databaseName demodatabase -sqlUserName  -sqlPassword  -sqlInline "select getdate()" -connectionString  -ErrorVariable errors -ConnectionTimeout 120 | Out-String
2019-05-08T17:44:56.3903602Z Temporary inline SQL file: C:\Users\VssAdministrator\AppData\Local\Temp\tmp6824.tmp
2019-05-08T17:44:56.4094244Z Invoke-Sqlcmd -connectionString "Data Source=demoserver.database.windows.net; Initial Catalog=demodatabase; Authentication=Active Directory Integrated;"  -Inputfile "C:\Users\VssAdministrator\AppData\Local\Temp\tmp6824.tmp"
2019-05-08T17:45:01.3106772Z ##[debug]Removing File C:\Users\VssAdministrator\AppData\Local\Temp\tmp6824.tmp
2019-05-08T17:45:01.3177919Z ##[debug]Failed to reach SQL server demoserver.database.windows.net. One or more errors occurred.
2019-05-08T17:45:01.3256036Z ##[debug]Error Message : System.Management.Automation.ActionPreferenceStopException: The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: One or more errors occurred.
2019-05-08T17:45:01.3268924Z ##[debug]   at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
2019-05-08T17:45:01.3282131Z ##[debug]   at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
2019-05-08T17:45:01.3294469Z ##[debug]   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
2019-05-08T17:45:01.3306333Z ##[debug]   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
2019-05-08T17:45:01.3323803Z ##[debug]Message To Parse: System.Management.Automation.ActionPreferenceStopException: The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: One or more errors occurred.
2019-05-08T17:45:01.3336914Z ##[debug]   at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
2019-05-08T17:45:01.3348860Z ##[debug]   at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
2019-05-08T17:45:01.3360481Z ##[debug]   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
2019-05-08T17:45:01.3373282Z ##[debug]   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
2019-05-08T17:45:01.3461566Z ##[debug]
2019-05-08T17:45:01.3658976Z Temporary inline SQL file: C:\Users\VssAdministrator\AppData\Local\Temp\tmp7B8E.tmp
2019-05-08T17:45:01.3678332Z Invoke-Sqlcmd -connectionString "Data Source=demoserver.database.windows.net; Initial Catalog=demodatabase; Authentication=Active Directory Integrated;"  -Inputfile "C:\Users\VssAdministrator\AppData\Local\Temp\tmp7B8E.tmp"
2019-05-08T17:45:01.5110410Z ##[debug]Removing File C:\Users\VssAdministrator\AppData\Local\Temp\tmp7B8E.tmp
2019-05-08T17:45:01.5186309Z ##[debug]No Firewall Rule was added
2019-05-08T17:45:01.5410661Z ##[debug]Caught exception from task script.
2019-05-08T17:45:01.5440006Z ##[debug]Error record:
2019-05-08T17:45:01.6073859Z ##[debug]One or more errors occurred.Check out how to troubleshoot failures at https://aka.ms/sqlazuredeployreadme#troubleshooting-
2019-05-08T17:45:01.6087196Z ##[debug]At D:\a\_tasks\SqlAzureDacpacDeployment_ce85a08b-a538-4d2b-8589-1d37a9ab970f\1.3.16\DeploySqlAzure.ps1:202 char:5
2019-05-08T17:45:01.6100074Z ##[debug]+     throw $errorMessage
2019-05-08T17:45:01.6113872Z ##[debug]+     ~~~~~~~~~~~~~~~~~~~
2019-05-08T17:45:01.6126477Z ##[debug]    + CategoryInfo          : OperationStopped: (One or more err...roubleshooting-:String) [], RuntimeException
2019-05-08T17:45:01.6137940Z ##[debug]    + FullyQualifiedErrorId : One or more errors occurred.Check out how to troubleshoot failures at https://aka.ms/sql    azuredeployreadme#troubleshooting-
2019-05-08T17:45:01.6149271Z ##[debug]
2019-05-08T17:45:01.6166593Z ##[debug]Script stack trace:
2019-05-08T17:45:01.6202488Z ##[debug]at <ScriptBlock>, D:\a\_tasks\SqlAzureDacpacDeployment_ce85a08b-a538-4d2b-8589-1d37a9ab970f\1.3.16\DeploySqlAzure.ps1: line 202
2019-05-08T17:45:01.6213523Z ##[debug]at <ScriptBlock>, <No file>: line 1
2019-05-08T17:45:01.6225421Z ##[debug]at <ScriptBlock>, <No file>: line 22
2019-05-08T17:45:01.6237258Z ##[debug]at <ScriptBlock>, <No file>: line 18
2019-05-08T17:45:01.6250995Z ##[debug]at <ScriptBlock>, <No file>: line 1
2019-05-08T17:45:01.6269245Z ##[debug]Exception:
2019-05-08T17:45:01.6310341Z ##[debug]System.Management.Automation.RuntimeException: One or more errors occurred.Check out how to troubleshoot failures at https://aka.ms/sqlazuredeployreadme#troubleshooting-
2019-05-08T17:45:01.6521044Z ##[error]One or more errors occurred.Check out how to troubleshoot failures at https://aka.ms/sqlazuredeployreadme#troubleshooting-
</code>```

答:
Check this https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/deploy/sql-azure-dacpac-deployment?view=azure-devops.

Authentication Type (Required) Type of database authentication, can be SQL Server Authentication, Active Directory - Integrated, Active Directory - Password, or Connection String. Integrated authentication means that the agent will access the database using its current Active Directory account context.

ContentLicense: CC BY-SA 4.0

Body:
I want to add an AD-Group to SQL Azure using Azure Devops. The AD group contains MSI of a webapp.

We've added a group to the AAD called DemoSqlAdmin, containing the SPN used in the Azure DevOps pipeline. This group has been set as the SQL Server - Active Directory admin.

When running the Azure Devops Task: Azure SQL Database Deployment with Authentication Type 'Active Directory - Integrated' we get the following error:

2019-05-08T17:44:56.3763560Z ##[debug]Run-InlineSql -authenticationType aadAuthenticationIntegrated -serverName demoserver.database.windows.net -databaseName demodatabase -sqlUserName  -sqlPassword  -sqlInline "select getdate()" -connectionString  -ErrorVariable errors -ConnectionTimeout 120 | Out-String
2019-05-08T17:44:56.3903602Z Temporary inline SQL file: C:\Users\VssAdministrator\AppData\Local\Temp\tmp6824.tmp
2019-05-08T17:44:56.4094244Z Invoke-Sqlcmd -connectionString "Data Source=demoserver.database.windows.net; Initial Catalog=demodatabase; Authentication=Active Directory Integrated;"  -Inputfile "C:\Users\VssAdministrator\AppData\Local\Temp\tmp6824.tmp"
2019-05-08T17:45:01.3106772Z ##[debug]Removing File C:\Users\VssAdministrator\AppData\Local\Temp\tmp6824.tmp
2019-05-08T17:45:01.3177919Z ##[debug]Failed to reach SQL server demoserver.database.windows.net. One or more errors occurred.
2019-05-08T17:45:01.3256036Z ##[debug]Error Message : System.Management.Automation.ActionPreferenceStopException: The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: One or more errors occurred.
2019-05-08T17:45:01.3268924Z ##[debug]   at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
2019-05-08T17:45:01.3282131Z ##[debug]   at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
2019-05-08T17:45:01.3294469Z ##[debug]   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
2019-05-08T17:45:01.3306333Z ##[debug]   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
2019-05-08T17:45:01.3323803Z ##[debug]Message To Parse: System.Management.Automation.ActionPreferenceStopException: The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: One or more errors occurred.
2019-05-08T17:45:01.3336914Z ##[debug]   at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
2019-05-08T17:45:01.3348860Z ##[debug]   at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
2019-05-08T17:45:01.3360481Z ##[debug]   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
2019-05-08T17:45:01.3373282Z ##[debug]   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
2019-05-08T17:45:01.3461566Z ##[debug]
2019-05-08T17:45:01.3658976Z Temporary inline SQL file: C:\Users\VssAdministrator\AppData\Local\Temp\tmp7B8E.tmp
2019-05-08T17:45:01.3678332Z Invoke-Sqlcmd -connectionString "Data Source=demoserver.database.windows.net; Initial Catalog=demodatabase; Authentication=Active Directory Integrated;"  -Inputfile "C:\Users\VssAdministrator\AppData\Local\Temp\tmp7B8E.tmp"
2019-05-08T17:45:01.5110410Z ##[debug]Removing File C:\Users\VssAdministrator\AppData\Local\Temp\tmp7B8E.tmp
2019-05-08T17:45:01.5186309Z ##[debug]No Firewall Rule was added
2019-05-08T17:45:01.5410661Z ##[debug]Caught exception from task script.
2019-05-08T17:45:01.5440006Z ##[debug]Error record:
2019-05-08T17:45:01.6073859Z ##[debug]One or more errors occurred.Check out how to troubleshoot failures at https://aka.ms/sqlazuredeployreadme#troubleshooting-
2019-05-08T17:45:01.6087196Z ##[debug]At D:\a\_tasks\SqlAzureDacpacDeployment_ce85a08b-a538-4d2b-8589-1d37a9ab970f\1.3.16\DeploySqlAzure.ps1:202 char:5
2019-05-08T17:45:01.6100074Z ##[debug]+     throw $errorMessage
2019-05-08T17:45:01.6113872Z ##[debug]+     ~~~~~~~~~~~~~~~~~~~
2019-05-08T17:45:01.6126477Z ##[debug]    + CategoryInfo          : OperationStopped: (One or more err...roubleshooting-:String) [], RuntimeException
2019-05-08T17:45:01.6137940Z ##[debug]    + FullyQualifiedErrorId : One or more errors occurred.Check out how to troubleshoot failures at https://aka.ms/sql    azuredeployreadme#troubleshooting-
2019-05-08T17:45:01.6149271Z ##[debug]
2019-05-08T17:45:01.6166593Z ##[debug]Script stack trace:
2019-05-08T17:45:01.6202488Z ##[debug]at


问:
How can I fill a listbox like this with data
What's the c# code to fill these listbox with datas (strings)

I saw this on https://learn.microsoft.com/en-us/dotnet/framework/wpf/data/data-templating-overview

but there's no C# Code.

I want to have a listbox like in "Defining a Simple DataTemplate" on the link
https://learn.microsoft.com/en-us/dotnet/framework/wpf/data/data-templating-overview

Picture from listbox   [1]: https://i.stack.imgur.com/K4HZS.png

```<code><ListBox Width="400" Margin="10"
         ItemsSource="{Binding Source={StaticResource myTodoList}}">
   <ListBox.ItemTemplate>
     <DataTemplate>
       <StackPanel>
         <TextBlock Text="{Binding Path=TaskName}" />
         <TextBlock Text="{Binding Path=Description}"/>
         <TextBlock Text="{Binding Path=Priority}"/>
       </StackPanel>
     </DataTemplate>
   </ListBox.ItemTemplate>
 </ListBox>
</code>```

答:
You should have something like this.

MainWindow.xaml.cs:

```<code>public List<ToDo> ToDoList {get; set;}

public MainWindow()
{
    InitializeComponent();
    DataContext=this;
    ToDoList= new List<ToDo>()
        {
            new ToDo{TaskName="Task1",Description="First Task"},
            new ToDo{TaskName="Task2",Description="Second Task"}
        };
}
</code>```

ToDo.cs:

```<code>public class ToDo
{
    public string TaskName {get; set;}
    public string Description {get; set;}
}
</code>```

Modify your Binding expression to:

```<code><ListBox Width="400" Margin="10"
     ItemsSource="{Binding ToDoList}">
</code>```

Body:
What's the c# code to fill these listbox with datas (strings)

I saw this on https://learn.microsoft.com/en-us/dotnet/framework/wpf/data/data-templating-overview

but there's no C# Code.

I want to have a listbox like in "Defining a Simple DataTemplate" on the link
https://learn.microsoft.com/en-us/dotnet/framework/wpf/data/data-templating-overview

Picture from listbox   [1]: https://i.stack.imgur.com/K4HZS.png

<ListBox Width="400" Margin="10"
         ItemsSource="{Binding Source={StaticResource myTodoList}}">
   <ListBox.ItemTemplate>
     <DataTemplate>
       <StackPanel>
         <TextBlock Text="{Binding Path=TaskName}" />
         <TextBlock Text="{Binding Path=Description}"/>
         <TextBlock Text="{Binding Path=Priority}"/>
       </StackPanel>
     </DataTemplate>
   </ListBox.ItemTemplate>
 </ListBox>

Body:
You should have something like this.

MainWindow.xaml.cs:

public List<ToDo> ToDoList {get; set;}

public MainWindow()
{
    InitializeComponent();
    DataContext=this;
    ToDoList= new List<ToDo>()
        {
            new ToDo{TaskName="Task1",Description="First Task"},
            new ToDo{TaskName="Task2",Description="Second Task"}
        };
}

ToDo.cs:

public class ToDo
{
    public string TaskName {get; set;}
    public string Description {get; set;}
}

Modify your Binding expression to:

<ListBox Width="400" Margin="10"
     ItemsSource="{Binding ToDoList}">


问:
my second double-click function not working
When clicking on a specific div, I want another div to create a new p style with text in it. </p>

<p>The first function created worked fine- whoever the second one seems to overrule the first one. I've tried changing the names of basically everything but it still seems to overrule. How could I solve this? </p>

```<code>  var para = document.createElement("P");
  para.innerHTML = "The Siamese crocodiles share one stomach, yet they fight over food.";
  document.getElementById("information").appendChild(para);
}
    window.onload = function() {
        document.getElementById("i29").ondblclick = function i29i() {
            i29();
        }
    }

function i3() {
  var para = document.createElement("P");
  para.innerHTML = "When you climb a good tree, you are given a push.";
  document.getElementById("information").appendChild(para);
}

    window.onload = function() {
        document.getElementById("i3").ondblclick = function i3i() {
            i3();
        }
    }```
</code>```

答:
you are resetting the window.onload to another value when you assign it to a different function twice. The simplest solution would be to do the following:</p>

```<code>window.onload = function() {
    document.getElementById("i29").ondblclick = i29;
    document.getElementById("i3").ondblclick = i3;
}
</code>```

Body:
When clicking on a specific div, I want another div to create a new p style with text in it.

The first function created worked fine- whoever the second one seems to overrule the first one. I've tried changing the names of basically everything but it still seems to overrule. How could I solve this?

  var para = document.createElement("P");
  para.innerHTML = "The Siamese crocodiles share one stomach, yet they fight over food.";
  document.getElementById("information").appendChild(para);
}
    window.onload = function() {
        document.getElementById("i29").ondblclick = function i29i() {
            i29();
        }
    }

function i3() {
  var para = document.createElement("P");
  para.innerHTML = "When you climb a good tree, you are given a push.";
  document.getElementById("information").appendChild(para);
}

    window.onload = function() {
        document.getElementById("i3").ondblclick = function i3i() {
            i3();
        }
    }```

Body:
you are resetting the window.onload to another value when you assign it to a different function twice. The simplest solution would be to do the following:

window.onload = function() {
    document.getElementById("i29").ondblclick = i29;
    document.getElementById("i3").ondblclick = i3;
}


问:
React component not re-rendering on state change using setState
I have a HomeScreen component which has button. I am trying to popup a modelview(Seperate component ie PopUpView) on the button click. In PopUpView i am sending its visibility as prop (isVisible).On the click of the button i am trying to change the state value popUpIsVisible from false to true. Hoping that this would re-render and popup my model view(Note this is working fine if i explicitly pass true). However with the state change it look like the render function is not being called and the popUp is not being displayed. Thanks for your help in advance

```<code>import React from 'react';
import { View, StyleSheet, Text, Button, TouchableHighlight, Alert, Dimensions} from 'react-native';
import { createStackNavigator, createAppContainer } from 'react-navigation';
import PopUpView from './src/PopUpView';

class HomeScreen extends React.Component {

  constructor(props) {
      super(props);
      this.state = {
        popUpIsVisible: false,
      };
    }

  setPopUpIsVisible(isVisible){
    this.setState({popUpIsVisible: isVisible });
  }

  render() {
    this.setPopUpIsVisible = this.setPopUpIsVisible.bind(this);
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor:"blue" }}>
        <Text>Home Screen</Text>
          <PopUpView isVisible={this.state.popUpIsVisible}/>
          <Button onPress={() => {this.setPopUpIsVisible(true)}}  title="Open PopUp Screen"/>
      </View>
    );
  }
}

const RootStack = createStackNavigator(
  {
    Home: HomeScreen
  },
  {
    initialRouteName: 'Home',
  }
);

const AppContainer = createAppContainer(RootStack);

export default class App extends React.Component {
  render() {
    return <AppContainer />;
  }
}
</code>```

PopUpView.js

```<code>import React from 'react';
import { View, Modal,StyleSheet, Text, TouchableOpacity, Dimensions} from 'react-native';
import { TabView, TabBar,SceneMap } from 'react-native-tab-view';
import Icon from 'react-native-vector-icons/SimpleLineIcons';

const FirstRoute = () => (
  <View style={{ flex: 1, backgroundColor: '#ff4081' }} />
);
const SecondRoute = () => (
  <View style={{ flex: 1, backgroundColor: '#673ab7' }} />
);
const ThirdRoute = () => (
  <View style={{ flex: 1, backgroundColor: '#673ab7' }} />
);

export default class PopUpView extends React.Component {
  constructor(props) {
      super(props);
      this.state = {
          modalVisible:this.props.isVisible,
          index: 0,
          routes: [
            { key: 'first', title: 'HIGHLIGHTS' },
            { key: 'second', title: 'AMENITIES' },
            { key: 'third', title: 'FACILITIES' },
          ],
        };
    }
    setModalVisible(visible) {
      this.setState({modalVisible: visible});
    }

renderHeader = props => <TabBar
    {...props}
    indicatorStyle={{backgroundColor: 'red'}}
    tabStyle={styles.bubble}
    labelStyle={styles.noLabel}
/>;

  render() {
      return (
      <Modal
          animationType="slide"
          transparent={true}
          visible={this.state.modalVisible}
          onRequestClose={() => {
            Alert.alert('Modal has been closed.');
          }}>
          <View style={styles.container}>
            <View style={styles.navBar}>
              <Text style={styles.navBarTitle}>Test</Text>
              <TouchableOpacity
                onPress={() => {
                  this.setModalVisible(!this.state.modalVisible);
                }}>
              <Icon style={styles.closeButton} name="close" size={35} color="grey" />
              </TouchableOpacity>
            </View>
            <TabView
              navigationState={this.state}
              renderScene={SceneMap({
                first: FirstRoute,
                second: SecondRoute,
                third: ThirdRoute,
                })}
              onIndexChange={index => this.setState({ index })}
              initialLayout={{ width: Dimensions.get('window').width }}
              renderTabBar={props =>
                      <TabBar
                          {...props}
                          style={{ backgroundColor: 'white' }}
                          indicatorStyle={{backgroundColor: 'black'}}
                          tabStyle={styles.bubble}
                          labelStyle={styles.label}
                      />
                  }
              />
          </View>
        </Modal>
      );
    }
}

const styles = StyleSheet.create({
  container: {
    flex:1,
    margin: 50,
    marginLeft: 20,
    marginRight: 20,
    marginBottom: 20,
    backgroundColor: "white",
    borderWidth: 1,
    borderColor: "grey",
    flexDirection: 'column'
  },
  navBar:{
    height:70,
    justifyContent: 'space-between',
    alignItems: 'center',
    flexDirection: 'row',
    borderBottomColor: 'lightgrey',
    borderBottomWidth: 1,
  },
  navBarTitle:{
    fontSize: 25,
    fontFamily: 'Optima',
    paddingLeft:15,
  },
  closeButton:{
    paddingRight:12,
  },
  label: {
        color: 'black'
    }
})
</code>```

答:
The problem with your code is that you are using the state inside the PopUpView which does not change when you change the external prop. to fix this you should use the componentwillreceiveprops and update your state accordingly.

```<code>componentWillReceiveProps(nextProps){
  if(this.props.isVisible!=nextProps.isVisible){
    this.setState({modalVisible:nextProps.isVisible})
  }
}
</code>```

The better approach will be using the this.props.isVisible as the visible prop for the Model.
In this scenario you will have to pass a function as a prop to popupview which will set the popUpIsVisible to false.
Something like below

```<code> <PopUpView isVisible={this.state.popUpIsVisible}
            onDismiss={()=>{this.setState({popUpIsVisible:false})}}/>
</code>```

You can call the onDismiss inside the child as

```<code><Modal visible={this.props.isVisible}>
<TouchableHighlight
    onPress={() => {
      this.props.onDismiss();
    }}>
 <Text>Hide Modal</Text>
</TouchableHighlight>
</Modal>
</code>```

The second approach is better as the visibility of the child is controlled by the parent.

Body:
I have a HomeScreen component which has button. I am trying to popup a modelview(Seperate component ie PopUpView) on the button click. In PopUpView i am sending its visibility as prop (isVisible).On the click of the button i am trying to change the state value popUpIsVisible from false to true. Hoping that this would re-render and popup my model view(Note this is working fine if i explicitly pass true). However with the state change it look like the render function is not being called and the popUp is not being displayed. Thanks for your help in advance

import React from 'react';
import { View, StyleSheet, Text, Button, TouchableHighlight, Alert, Dimensions} from 'react-native';
import { createStackNavigator, createAppContainer } from 'react-navigation';
import PopUpView from './src/PopUpView';

class HomeScreen extends React.Component {

  constructor(props) {
      super(props);
      this.state = {
        popUpIsVisible: false,
      };
    }

  setPopUpIsVisible(isVisible){
    this.setState({popUpIsVisible: isVisible });
  }

  render() {
    this.setPopUpIsVisible = this.setPopUpIsVisible.bind(this);
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor:"blue" }}>
        <Text>Home Screen</Text>
          <PopUpView isVisible={this.state.popUpIsVisible}/>
          <Button onPress={() => {this.setPopUpIsVisible(true)}}  title="Open PopUp Screen"/>
      </View>
    );
  }
}

const RootStack = createStackNavigator(
  {
    Home: HomeScreen
  },
  {
    initialRouteName: 'Home',
  }
);

const AppContainer = createAppContainer(RootStack);

export default class App extends React.Component {
  render() {
    return <AppContainer />;
  }
}

PopUpView.js

import React from 'react';
import { View, Modal,StyleSheet, Text, TouchableOpacity, Dimensions} from 'react-native';
import { TabView, TabBar,SceneMap } from 'react-native-tab-view';
import Icon from 'react-native-vector-icons/SimpleLineIcons';

const FirstRoute = () => (
  <View style={{ flex: 1, backgroundColor: '#ff4081' }} />
);
const SecondRoute = () => (
  <View style={{ flex: 1, backgroundColor: '#673ab7' }} />
);
const ThirdRoute = () => (
  <View style={{ flex: 1, backgroundColor: '#673ab7' }} />
);

export default class PopUpView extends React.Component {
  constructor(props) {
      super(props);
      this.state = {
          modalVisible:this.props.isVisible,
          index: 0,
          routes: [
            { key: 'first', title: 'HIGHLIGHTS' },
            { key: 'second', title: 'AMENITIES' },
            { key: 'third', title: 'FACILITIES' },
          ],
        };
    }
    setModalVisible(visible) {
      this.setState({modalVisible: visible});
    }

renderHeader = props => <TabBar
    {...props}
    indicatorStyle={{backgroundColor: 'red'}}
    tabStyle={styles.bubble}
    labelStyle={styles.noLabel}
/>;

  render() {
      return (
      <Modal
          animationType="slide"
          transparent={true}
          visible={this.state.modalVisible}
          onRequestClose={() => {
            Alert.alert('Modal has been closed.');
          }}>
          <View style={styles.container}>
            <View style={styles.navBar}>
              <Text style={styles.navBarTitle}>Test</Text>
              <TouchableOpacity
                onPress={() => {
                  this.setModalVisible(!this.state.modalVisible);
                }}>
              <Icon style={styles.closeButton} name="close" size={35} color="grey" />
              </TouchableOpacity>
            </View>
            <TabView
              navigationState={this.state}
              renderScene={SceneMap({
                first: FirstRoute,
                second: SecondRoute,
                third: ThirdRoute,
                })}
              onIndexChange={index => this.setState({ index })}
              initialLayout={{ width: Dimensions.get('window').width }}
              renderTabBar={props =>
                      <TabBar
                          {...props}
                          style={{ backgroundColor: 'white' }}
                          indicatorStyle={{backgroundColor: 'black'}}
                          tabStyle={styles.bubble}
                          labelStyle={styles.label}
                      />
                  }
              />
          </View>
        </Modal>
      );
    }
}

const styles = StyleSheet.create({
  container: {
    flex:1,
    margin: 50,
    marginLeft: 20,
    marginRight: 20,
    marginBottom: 20,
    backgroundColor: "white",
    borderWidth: 1,
    borderColor: "grey",
    flexDirection: 'column'
  },
  navBar:{
    height:70,
    justifyContent: 'space-between',
    alignItems: 'center',
    flexDirection: 'row',
    borderBottomColor: 'lightgrey',
    borderBottomWidth: 1,
  },
  navBarTitle:{
    fontSize: 25,
    fontFamily: 'Optima',
    paddingLeft:15,
  },
  closeButton:{
    paddingRight:12,
  },
  label: {
        color: 'black'
    }
})

Body:
The problem with your code is that you are using the state inside the PopUpView which does not change when you change the external prop. to fix this you should use the componentwillreceiveprops and update your state accordingly.

componentWillReceiveProps(nextProps){
  if(this.props.isVisible!=nextProps.isVisible){
    this.setState({modalVisible:nextProps.isVisible})
  }
}

The better approach will be using the this.props.isVisible as the visible prop for the Model.
In this scenario you will have to pass a function as a prop to popupview which will set the popUpIsVisible to false.
Something like below

 <PopUpView isVisible={this.state.popUpIsVisible}
            onDismiss={()=>{this.setState({popUpIsVisible:false})}}/>

You can call the onDismiss inside the child as

<Modal visible={this.props.isVisible}>
<TouchableHighlight
    onPress={() => {
      this.props.onDismiss();
    }}>
 <Text>Hide Modal</Text>
</TouchableHighlight>
</Modal>

The second approach is better as the visibility of the child is controlled by the parent.


问:
Get table row text python selenium
This is the html

```<code><table id="dataLstSubCat" cellspacing="0" style="border-collapse:collapse;">
    <tbody><tr>
        <td style="font-weight:normal;font-style:normal;text-decoration:none;white-space:nowrap;">
                        <a onclick="ShowHideProduct();" id="dataLstSubCat_LnkBtnSubCat_0" href="javascript:__doPostBack('dataLstSubCat$ctl00$LnkBtnSubCat','')">Primers</a>
                      </td><td style="font-weight:normal;font-style:normal;text-decoration:none;white-space:nowrap;">
                        <a onclick="ShowHideProduct();" id="dataLstSubCat_LnkBtnSubCat_1" href="javascript:__doPostBack('dataLstSubCat$ctl01$LnkBtnSubCat','')">Intermediates</a>
                      </td><td style="font-weight:normal;font-style:normal;text-decoration:none;white-space:nowrap;">
                        <a onclick="ShowHideProduct();" id="dataLstSubCat_LnkBtnSubCat_2" href="javascript:__doPostBack('dataLstSubCat$ctl02$LnkBtnSubCat','')">Finishes</a>
                      </td>
    </tr>
</tbody></table>
</code>```

Now I want to extract the table data(td) text
like I want to extract the text

[Primers,Intermediates,Finishes]

This is what I have tried

```<code>new_text=driver.find_element_by_xpath(("//table[@id='dataLstSubCat']/tbody/tr"))
new_text.text
</code>```

which gives o/p in string and not in list

```<code>Primers Intermediates Finishes
</code>```

Is there any way by which it can be done.

答:
To extract the table data [Primers,Intermediates,Finishes] you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

```<code>print([my_text_elem.get_attribute("innerHTML") for my_text_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "table#dataLstSubCat>tbody>tr td>a")))])
</code>```

Using XPATH:

```<code>print([my_text_elem.get_attribute("innerHTML") for my_text_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.XPATH, "//table[@id='dataLstSubCat']/tbody/tr//td/a")))])
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Title: Get table row text python selenium

Body:
This is the html

                        Primers

                        Intermediates

                        Finishes

Now I want to extract the table data(td) text
like I want to extract the text

[Primers,Intermediates,Finishes]

This is what I have tried

new_text=driver.find_element_by_xpath(("//table[@id='dataLstSubCat']/tbody/tr"))
new_text.text

which gives o/p in string and not in list

Primers Intermediates Finishes

Is there any way by which it can be done.

Body:
To extract the table data [Primers,Intermediates,Finishes] you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

print([my_text_elem.get_attribute("innerHTML") for my_text_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "table#dataLstSubCat>tbody>tr td>a")))])

Using XPATH:

print([my_text_elem.get_attribute("innerHTML") for my_text_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.XPATH, "//table[@id='dataLstSubCat']/tbody/tr//td/a")))])

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC


问:
How to get swf's url on swc library
I'am a beginner of ActionScript3

I wanna get swf's url.

but I develop swc lib.
swf(Main) develop other developer.

I have to get from Main loaderinfo, I / F is already fixed.

Do you have a good idea?

```<code>public function doSomething( arg1:String,arg2:String ):String
{
    /* some thing */

    return result;
}
</code>```

答:
Get the other developer to pass in the Main class or the Stage (in fact any DisplayObject) and return the loaderInfo.loaderURL from that. Something like:

```<code>public function getSWFURL( dObj:Sprite ):String
{
    return dObj.root.loaderInfo.loaderURL;
}
</code>```

the .root will return the root DisplayObject, so any DisplayObject that's attached to the stage will return this.

ContentLicense: CC BY-SA 3.0

Title: How to get swf's url on swc library

Body:
I'am a beginner of ActionScript3

I wanna get swf's url.

but I develop swc lib.
swf(Main) develop other developer.

I have to get from Main loaderinfo, I / F is already fixed.

Do you have a good idea?

public function doSomething( arg1:String,arg2:String ):String
{
    /* some thing */

    return result;
}

Body:
Get the other developer to pass in the Main class or the Stage (in fact any DisplayObject) and return the loaderInfo.loaderURL from that. Something like:

public function getSWFURL( dObj:Sprite ):String
{
    return dObj.root.loaderInfo.loaderURL;
}

the .root will return the root DisplayObject, so any DisplayObject that's attached to the stage will return this.


问:
Is there a way to have my checkboxes alinged horizontally with a fixed number using bootstrap?
I don't want my checkboxes under each other but alinged next to each other. But only in columns of 5 for example.

At the moment I have something like this:

Checkboxes vertical

But i want this:

```<code>[x] label [x] label [x] label [x] label [x] label
[x] label [x] label [x] label [x] label [x] label
</code>```

This is my code:

```<code>      <div class="row form-group">
        <div class="col col-md-3">
          <a data-toggle="collapse" href="#collapsKlassen">
            <h5 class="mb-0">
              Klassen <i class="fas fa-angle-down rotate-icon"></i>
            </h5>
          </a>
        </div>
        <div class="col-12 col-md-9 collapse" id="collapsKlassen"style="margin-right: 5px;">
          <div class="form-check  "  >
            <div >
              @Html.EditorFor(x => x.CheckBoxKlassen)
            </div>
          </div>
        </div>
      </div>
</code>```

Already tried with formcheck inline etc, but not giving result.
 EDIT:
Rendered code:

```<code><input id="CheckBoxKlassen_0__ID" name="CheckBoxKlassen[0].ID" type="hidden" value="61" />
<input id="CheckBoxKlassen_0__Display" name="CheckBoxKlassen[0].Display" type="hidden" value="BIO 1Aa" />
<input data-val="true" data-val-required="The WasChecked field is required." id="CheckBoxKlassen_0__WasChecked" name="CheckBoxKlassen[0].WasChecked" type="hidden" value="False" />
<input data-val="true" data-val-required="The IsChecked field is required." id="CheckBoxKlassen_0__IsChecked" name="CheckBoxKlassen[0].IsChecked" type="checkbox" value="true" />
<label for="CheckBoxKlassen_0__IsChecked">BIO 1Aa</label>
<br /><input id="CheckBoxKlassen_1__ID" name="CheckBoxKlassen[1].ID" type="hidden" value="64" />
<input id="CheckBoxKlassen_1__Display" name="CheckBoxKlassen[1].Display" type="hidden" value="BIO 1Ab" />
<input data-val="true" data-val-required="The WasChecked field is required." id="CheckBoxKlassen_1__WasChecked" name="CheckBoxKlassen[1].WasChecked" type="hidden" value="False" />
<input data-val="true" data-val-required="The IsChecked field is required." id="CheckBoxKlassen_1__IsChecked" name="CheckBoxKlassen[1].IsChecked" type="checkbox" value="true" />
<label for="CheckBoxKlassen_1__IsChecked">BIO 1Ab</label>
<br /><input id="CheckBoxKlassen_2__ID" name="CheckBoxKlassen[2].ID" type="hidden" value="58" />
<input id="CheckBoxKlassen_2__Display" name="CheckBoxKlassen[2].Display" type="hidden" value="BIO 1Ac" />
<input data-val="true" data-val-required="The WasChecked field is required." id="CheckBoxKlassen_2__WasChecked" name="CheckBoxKlassen[2].WasChecked" type="hidden" value="False" />
<input data-val="true" data-val-required="The IsChecked field is required." id="CheckBoxKlassen_2__IsChecked" name="CheckBoxKlassen[2].IsChecked" type="checkbox" value="true" />
<label for="CheckBoxKlassen_2__IsChecked">BIO 1Ac</label>
<br /><input id="CheckBoxKlassen_3__ID" name="CheckBoxKlassen[3].ID" type="hidden" value="71" />
<input id="CheckBoxKlassen_3__Display" name="CheckBoxKlassen[3].Display" type="hidden" value="BIO 1Ad" />
<input data-val="true" data-val-required="The WasChecked field is required." id="CheckBoxKlassen_3__WasChecked" name="CheckBoxKlassen[3].WasChecked" type="hidden" value="False" />
<input data-val="true" data-val-required="The IsChecked field is required." id="CheckBoxKlassen_3__IsChecked" name="CheckBoxKlassen[3].IsChecked" type="checkbox" value="true" />
<label for="CheckBoxKlassen_3__IsChecked">BIO 1Ad</label>
<br /><input id="CheckBoxKlassen_4__ID" name="CheckBoxKlassen[4].ID" type="hidden" value="59" />
</code>```

答:
Here is the working example , you could refer to and make the modification according to your need.

Model

```<code> public class CheckBoxKlassen
{
    public int Id { get; set; }
    public string Display { get; set; }

    public bool IsChecked { get; set; }
}

public class CheckBoxViewModel
{
    public IList<CheckBoxKlassen> CheckBoxKlassen { get; set; }
}
</code>```

CheckBoxList.cshtml , use the CSS to align checkboxes horizontally and change the width percent of
 to adjust the number of checkboxes per line.

```<code>@model WebApplication1.Models.CheckBoxViewModel
<style>
  .checkbox-grid li {
    display: block;
    float: left;
    width: 20%;
   }
</style>

<div class="row form-group">
  <div class="col col-md-3">
    <a data-toggle="collapse" href="#collapsKlassen">
        <h5 class="mb-0">
            Klassen <i class="fas fa-angle-down rotate-icon"></i>
        </h5>
    </a>
  </div>
  <div class="col-12 col-md-9 collapse" id="collapsKlassen" style="margin-right: 5px;">
    <div class="form-check  ">
        <ul class="checkbox-grid">
            @for (var i = 0; i < Model.CheckBoxKlassen.Count(); i++)
            {
            <li>
                <input type="checkbox" asp-for="CheckBoxKlassen[i].IsChecked" value="@Model.CheckBoxKlassen[i].Id" />
                <label >@Model.CheckBoxKlassen[i].Display</label>
            </li>

            }
        </ul>
    </div>
  </div>
</div>
</code>```

Controller , get the data of checkboxlist

```<code>public IActionResult CheckBoxList()
    {
        CheckBoxViewModel model = new CheckBoxViewModel()
        {
            CheckBoxKlassen = _context.CheckBoxKlassen.ToList()
        };
        return View(model);
    }
</code>```

Body:
I don't want my checkboxes under each other but alinged next to each other. But only in columns of 5 for example.

At the moment I have something like this:

Checkboxes vertical

But i want this:

[x] label [x] label [x] label [x] label [x] label
[x] label [x] label [x] label [x] label [x] label

This is my code:

              Klassen

              @Html.EditorFor(x => x.CheckBoxKlassen)

Already tried with formcheck inline etc, but not giving result.
 EDIT:
Rendered code:

<input id="CheckBoxKlassen_0__ID" name="CheckBoxKlassen[0].ID" type="hidden" value="61" />
<input id="CheckBoxKlassen_0__Display" name="CheckBoxKlassen[0].Display" type="hidden" value="BIO 1Aa" />
<input data-val="true" data-val-required="The WasChecked field is required." id="CheckBoxKlassen_0__WasChecked" name="CheckBoxKlassen[0].WasChecked" type="hidden" value="False" />
<input data-val="true" data-val-required="The IsChecked field is required." id="CheckBoxKlassen_0__IsChecked" name="CheckBoxKlassen[0].IsChecked" type="checkbox" value="true" />
BIO 1Aa

<input id="CheckBoxKlassen_1__ID" name="CheckBoxKlassen[1].ID" type="hidden" value="64" />
<input id="CheckBoxKlassen_1__Display" name="CheckBoxKlassen[1].Display" type="hidden" value="BIO 1Ab" />
<input data-val="true" data-val-required="The WasChecked field is required." id="CheckBoxKlassen_1__WasChecked" name="CheckBoxKlassen[1].WasChecked" type="hidden" value="False" />
<input data-val="true" data-val-required="The IsChecked field is required." id="CheckBoxKlassen_1__IsChecked" name="CheckBoxKlassen[1].IsChecked" type="checkbox" value="true" />
BIO 1Ab

<input id="CheckBoxKlassen_2__ID" name="CheckBoxKlassen[2].ID" type="hidden" value="58" />
<input id="CheckBoxKlassen_2__Display" name="CheckBoxKlassen[2].Display" type="hidden" value="BIO 1Ac" />
<input data-val="true" data-val-required="The WasChecked field is required." id="CheckBoxKlassen_2__WasChecked" name="CheckBoxKlassen[2].WasChecked" type="hidden" value="False" />
<input data-val="true" data-val-required="The IsChecked field is required." id="CheckBoxKlassen_2__IsChecked" name="CheckBoxKlassen[2].IsChecked" type="checkbox" value="true" />
BIO 1Ac

<input id="CheckBoxKlassen_3__ID" name="CheckBoxKlassen[3].ID" type="hidden" value="71" />
<input id="CheckBoxKlassen_3__Display" name="CheckBoxKlassen[3].Display" type="hidden" value="BIO 1Ad" />
<input data-val="true" data-val-required="The WasChecked field is required." id="CheckBoxKlassen_3__WasChecked" name="CheckBoxKlassen[3].WasChecked" type="hidden" value="False" />
<input data-val="true" data-val-required="The IsChecked field is required." id="CheckBoxKlassen_3__IsChecked" name="CheckBoxKlassen[3].IsChecked" type="checkbox" value="true" />
BIO 1Ad

<input id="CheckBoxKlassen_4__ID" name="CheckBoxKlassen[4].ID" type="hidden" value="59" />

Body:
Here is the working example , you could refer to and make the modification according to your need.

Model

 public class CheckBoxKlassen
{
    public int Id { get; set; }
    public string Display { get; set; }

    public bool IsChecked { get; set; }
}

public class CheckBoxViewModel
{
    public IList<CheckBoxKlassen> CheckBoxKlassen { get; set; }
}

CheckBoxList.cshtml , use the CSS to align checkboxes horizontally and change the width percent of <li> to adjust the number of checkboxes per line.

@model WebApplication1.Models.CheckBoxViewModel
<style>
  .checkbox-grid li {
    display: block;
    float: left;
    width: 20%;
   }
</style>

<div class="row form-group">
  <div class="col col-md-3">
    <a data-toggle="collapse" href="#collapsKlassen">
        <h5 class="mb-0">
            Klassen <i class="fas fa-angle-down rotate-icon"></i>
        </h5>
    </a>
  </div>
  <div class="col-12 col-md-9 collapse" id="collapsKlassen" style="margin-right: 5px;">
    <div class="form-check  ">
        <ul class="checkbox-grid">
            @for (var i = 0; i < Model.CheckBoxKlassen.Count(); i++)
            {
            <li>
                <input type="checkbox" asp-for="CheckBoxKlassen[i].IsChecked" value="@Model.CheckBoxKlassen[i].Id" />
                <label >@Model.CheckBoxKlassen[i].Display</label>
            </li>

            }
        </ul>
    </div>
  </div>
</div>

Controller , get the data of checkboxlist

public IActionResult CheckBoxList()
    {
        CheckBoxViewModel model = new CheckBoxViewModel()
        {
            CheckBoxKlassen = _context.CheckBoxKlassen.ToList()
        };
        return View(model);
    }


问:
Does ConfidentialClientApplication have a common cache for all instances?
There is an example on how to acquire token for client credentials with MSAL here. E.g.

```<code>var app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
    .WithAuthority(authority)
    .WithCertificate(certificate)
    .Build();
</code>```

Now this will create a new ConfidentialClientApplication each time, so I am wondering if the token cache inside will be shared?

I use it for KeyVault integration and authority comes from the key vault callback so I cannot compose ConfidentialClientApplication beforehand, so I am wondering if it's ok to do that every time, or then cache will be useless?

Alternatively I will have to remember instances of ConfidentialClientApplication per authority myself using some kind of lazy initialization.

答:
I got the answer myself, it is apparently very easy: I just did call two different ConfidentialClientApplication and compared tokens and they were different.

Also turned off network and the second cache call failed.

So that definitely means there is no shared cache involved.

Body:
There is an example on how to acquire token for client credentials with MSAL here. E.g.

var app = ConfidentialClientApplicationBuilder.Create(config.ClientId)
    .WithAuthority(authority)
    .WithCertificate(certificate)
    .Build();

Now this will create a new ConfidentialClientApplication each time, so I am wondering if the token cache inside will be shared?

I use it for KeyVault integration and authority comes from the key vault callback so I cannot compose ConfidentialClientApplication beforehand, so I am wondering if it's ok to do that every time, or then cache will be useless?

Alternatively I will have to remember instances of ConfidentialClientApplication per authority myself using some kind of lazy initialization.


问:
Deserializing xml namespaces with Jackson & Kotlin
I have a xml element with 2 namespaces, and I'm not able to read them with jackson.

<Person xmlns="http://some.namespace.com" xmlns:ns0="http://some.other.namespace.com">
    <name>John</name>
</Person>
```

```internal data class Person(
    val name: String,
    @get:JacksonXmlProperty(isAttribute = true)
    val xmlns: String,
    @get:JacksonXmlProperty(isAttribute = true, localName="xmlns:ns0")
    val ns0: String
)
```

<p>When reading the XML with jackson, I get an error saying that both namespaces should be nullable.</p>

<p>I've tried with some variants like attrs in the body of the class and with the namespace attribute, like</p>

```    @JacksonXmlProperty(isAttribute = true, localName = "ns0", namespace = "xmlns")
    var ns0: String? = null
```

<p>This is the mapper I'm using</p>

```val mapper: XmlMapper = XmlMapper().apply {
        registerModule(KotlinModule())
        setSerializationInclusion(JsonInclude.Include.NON_NULL)
    }
```

How can I read and write again this xml and make them identical?

答:
The XML parameters xmlns="...." and xmlns:prefix="...."
are XML namespace definitions. They are not XML attributes,
even if they look like this.

Hence, you must not define POJO attributes corresponding to the these.
Instead, you use the namespace parameter of @JacksonXmlProperty.
So your Person class will simply look like this:

```<code>internal data class Person(
    @get: JacksonXmlProperty(isAttribute=true, localName="name", namespace="http://some.namespace.com")
    val name: String
)
</code>```

Body:
I have a xml element with 2 namespaces, and I'm not able to read them with jackson.

<Person xmlns="http://some.namespace.com" xmlns:ns0="http://some.other.namespace.com">
    <name>John</name>
</Person>

internal data class Person(
    val name: String,
    @get:JacksonXmlProperty(isAttribute = true)
    val xmlns: String,
    @get:JacksonXmlProperty(isAttribute = true, localName="xmlns:ns0")
    val ns0: String
)

When reading the XML with jackson, I get an error saying that both namespaces should be nullable.

I've tried with some variants like attrs in the body of the class and with the namespace attribute, like

    @JacksonXmlProperty(isAttribute = true, localName = "ns0", namespace = "xmlns")
    var ns0: String? = null

This is the mapper I'm using

val mapper: XmlMapper = XmlMapper().apply {
        registerModule(KotlinModule())
        setSerializationInclusion(JsonInclude.Include.NON_NULL)
    }

How can I read and write again this xml and make them identical?

Body:
The XML parameters xmlns="...." and xmlns:prefix="...."
are XML namespace definitions. They are not XML attributes,
even if they look like this.

Hence, you must not define POJO attributes corresponding to the these.
Instead, you use the namespace parameter of @JacksonXmlProperty.
So your Person class will simply look like this:

internal data class Person(
    @get: JacksonXmlProperty(isAttribute=true, localName="name", namespace="http://some.namespace.com")
    val name: String
)


问:
wxPython: Create a log system
I have an application that calls another script when clicking on a button. On that script, I have some prints that I would like to display on a wx.TextCtrl widget on the application but I have no clue where to start.

This is an example of the script called:

```<code>#export.py

def exportData():
    #some code
    #Some prints that I would like to display on the application
</code>```

And here is how I call the script from the application:

```<code>def loadData(self, event):
    from export import exportData
    exportData()
</code>```

I have some questions:

I assume that print won't work as a log, and I have to use some kind of logging system. Is that correct? I've tried to use log.write but I keep getting "log not defined error".

Maybe calling exportData() directly from def loadData isn't the best way to proceed. If it's the case, what is the correct way?

Finally, How can I display the prints/logs into the wx.TextCtrl widget of the application?

Don't hesitate if you need more information. Thank you in advance for your help.

EDIT

Here is a minimalist working example code of what I'm trying to do. Printing "This is my log" in the main.py TextCtrl.

```<code># main.py
import wx, sys
import export

class Test(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, "Frame aka Window", size=(300, 200))
        panel = wx.Panel(self)
        log = wx.TextCtrl(panel, style=wx.TE_MULTILINE|wx.TE_READONLY)

        button = wx.Button(panel, label="Export", pos=(80, 80), size=(120, 30))

        self.Bind(wx.EVT_BUTTON, self.export, button)

        mySizer = wx.BoxSizer(wx.VERTICAL)
        mySizer.Add(button, 0, wx.ALL | wx.ALIGN_CENTER, 5)
        mySizer.Add(log, 0, wx.ALL | wx.ALIGN_CENTER, 5)

        panel.SetSizer(mySizer)

    def export(self, event):
        from export import exportData
        exportData()

if __name__ == '__main__':
    app = wx.App()
    frame = Test(parent=None, id=1)
    frame.Show()
    app.MainLoop()
</code>```

and the export file:

```<code>#export.py

def exportData():
    print("This is my log")
</code>```

答:
You could create a "Log" as an TextCtrl.

```<code>self.log = wx.TextCtrl(Panel, style=wx.TE_MULTILINE|wx.TE_READONLY)
</code>```

If you want to add something your could write it like this:

```<code>self.log.AppendText('Your String here')
</code>```

To clear it you do it like this:

```<code>self.log.Clear()
</code>```

To be more detailed we need to see more of your code. But maybe this will help you already.

Also i would import on top of your Module not inside a function.

```<code>from export import exportData

def loadData(self, event):
        exportData(yourLogData)
</code>```

I dont know where the information for you log are coming from but i would assume you need to pass it to exportData like this:

```<code>[...]
self.log = wx.TextCtrl(Panel, style=wx.TE_MULTILINE|wx.TE_READONLY)
[...]
def exportData(self, yourLogData):
    #some code
    #Some prints that I would like to display on the application
    self.log.AppendText(yourLogData)
</code>```

Title: wxPython: Create a log system

Body:
I have an application that calls another script when clicking on a button. On that script, I have some prints that I would like to display on a wx.TextCtrl widget on the application but I have no clue where to start.

This is an example of the script called:

#export.py

def exportData():
    #some code
    #Some prints that I would like to display on the application

And here is how I call the script from the application:

def loadData(self, event):
    from export import exportData
    exportData()

I have some questions:

I assume that print won't work as a log, and I have to use some kind of logging system. Is that correct? I've tried to use log.write but I keep getting "log not defined error".

Maybe calling exportData() directly from def loadData isn't the best way to proceed. If it's the case, what is the correct way?

Finally, How can I display the prints/logs into the wx.TextCtrl widget of the application?

Don't hesitate if you need more information. Thank you in advance for your help.

EDIT

Here is a minimalist working example code of what I'm trying to do. Printing "This is my log" in the main.py TextCtrl.

# main.py
import wx, sys
import export

class Test(wx.Frame):
    def __init__(self, parent, id):
        wx.Frame.__init__(self, parent, id, "Frame aka Window", size=(300, 200))
        panel = wx.Panel(self)
        log = wx.TextCtrl(panel, style=wx.TE_MULTILINE|wx.TE_READONLY)

        button = wx.Button(panel, label="Export", pos=(80, 80), size=(120, 30))

        self.Bind(wx.EVT_BUTTON, self.export, button)

        mySizer = wx.BoxSizer(wx.VERTICAL)
        mySizer.Add(button, 0, wx.ALL | wx.ALIGN_CENTER, 5)
        mySizer.Add(log, 0, wx.ALL | wx.ALIGN_CENTER, 5)

        panel.SetSizer(mySizer)

    def export(self, event):
        from export import exportData
        exportData()

if __name__ == '__main__':
    app = wx.App()
    frame = Test(parent=None, id=1)
    frame.Show()
    app.MainLoop()

and the export file:

#export.py

def exportData():
    print("This is my log")

Body:
You could create a "Log" as an TextCtrl.

self.log = wx.TextCtrl(Panel, style=wx.TE_MULTILINE|wx.TE_READONLY)

If you want to add something your could write it like this:

self.log.AppendText('Your String here')

To clear it you do it like this:

self.log.Clear()

To be more detailed we need to see more of your code. But maybe this will help you already.

Also i would import on top of your Module not inside a function.

from export import exportData

def loadData(self, event):
        exportData(yourLogData)

I dont know where the information for you log are coming from but i would assume you need to pass it to exportData like this:

[...]
self.log = wx.TextCtrl(Panel, style=wx.TE_MULTILINE|wx.TE_READONLY)
[...]
def exportData(self, yourLogData):
    #some code
    #Some prints that I would like to display on the application
    self.log.AppendText(yourLogData)


问:
Java: How to create torrent file for multiple files or directories?
The next code is a part of jBitTorrent API for Java a bit modified by me:
```
            if (!torr.saveAs.matches(""))
                info.put("name", torr.saveAs);
            else
                info.put("name", "noDirSpec");
            ArrayList files = new ArrayList();
            for (int i = 0; i < torr.name.size(); i++) {
                SortedMap file = new TreeMap();
                file.put("length", (Integer) torr.length.get(i));
//                String[] path = ((String) torr.name.get(i)).split("\\");
                String[] path = ((String) torr.name.get(i)).split("/");
                File f = new File((String)(torr.name.get(i)));
                ArrayList pathList = new ArrayList(path.length);</p>

```            if(f.isFile())
            {
                pathList.add(path[path.length - 1]);
            }
            else if(f.isDirectory())
            {
```

<p><b>//                    ???</b>
                }
```
This is torrent file(s) generation. So the «String[] path» is commented because of «\\» doesn't match linux slashes and generate invalid paths. Specification for multiple files is:

For the case of the multi-file mode, the info dictionary contains the following structure:
name: the filename of the directory in which to store all the files. This is purely advisory. (string)
files: a list of dictionaries, one for each file. Each dictionary in this list contains the following keys:
length: length of the file in bytes (integer)
md5sum: (optional) a 32-character hexadecimal string corresponding to the MD5 sum of the file. This is not used by BitTorrent at all, but it is included by some programs for greater compatibility.
path: a list containing one or more string elements that together represent the path and filename. Each element in the list corresponds to either a directory name or (in the case of the final element) the filename. For example, a the file "dir1/dir2/file.ext" would consist of three string elements: "dir1", "dir2", and "file.ext". This is encoded as a bencoded list of strings such as l4:dir14:dir28:file.exte

And for single file is:

For the case of the single-file mode, the info dictionary contains the following structure:
name: the filename. This is purely advisory. (string)
length: length of the file in bytes (integer)
md5sum: (optional) a 32-character hexadecimal string corresponding to the MD5 sum of the file. This is not used by BitTorrent at all, but it is included by some programs for greater compatibility.

So if I will use the previous code for single file here will be generated this torrent:

And torrent files contains:

d8:announce0:10:created by18:jBittorrentAPI 1.04:infod6:lengthi1645522e4:name27:ppkBB3cker-free-20101212.7z12:piece lengthi102400e6:pieces340:(ѕн‘xІZUЙ
ЃКХЪйкжѕЫ››3УМ‹ЁWпЖћA‡  ѕ,т C;НлАтжѓњЧ0x‡Е  %РъEЬ™сЖ®6ЦоёSЌ1пж`.бй%»†Ґ0VЩ%“ѕђoђџ'hЃ7ЦЭjъ\!RОQ.lВЦрjяGЋХ®^zЏ
ЎЉSЖЕ|„1D”кCРк+бћJLХmЛF`Ы"ГљSЪv$Л
Оuњi€ЙxQee

Okay. But how I should generate torrent for directory? The problem is that in unmodified API will be generated files with full path from root. But I need something like this:

And the valid torrent file is:

d10:created by25:Transmission/2.05 (11488)13:creation datei1302559094e8:encoding5:UTF-84:infod5:filesld6:lengthi196126e4:pathl29:1231190375_bulldozer.jar.parteed6:lengthi937518e4:pathl13:FIFA_2009-RPL35:240x320-fifa-rpl-2009(eng).jar.parteed6:lengthi802555e4:pathl13:FIFA_2009-RPL31:fifa-09-rpl_176x220_en.jar.parteed6:lengthi985098e4:pathl13:FIFA_2009-RPL36:FIFA_2009-RPL_240x320_(rus).jar.parteed6:lengthi138534e4:pathl41:GAZilaMarshrutkaUbiyca[game-torrent.info]41:GAZila_Marshrutka_Ubiyca_176x208.jar.parteed6:lengthi175851e4:pathl41:GAZilaMarshrutkaUbiyca[game-torrent.info]41:GAZila_Marshrutka_Ubiyca_240x320.jar.parteed6:lengthi827473e4:pathl33:God of War 3D (240х320).jar.parteed6:lengthi295164e4:pathl26:Men_In_Black-Alien_Assault39:Men_In_Black-Alien_Assault_176.jar.parteed6:lengthi374046e4:pathl26:Men_In_Black-Alien_Assault39:Men_In_Black-Alien_Assault_240.jar.parteee4:name53:5 отличных игр для мобильника12:piece lengthi32768e6:pieces2900:�dSI�%|Q�§I�I��oQ�CI�a1R�{ۦ��

答:
I recommend you use System.getProperty("file.separator") to create valid paths on all OS's instead of hardcoding it to the windows file separator (\)

I havent used this API, but looking at the following line..

For the case of the multi-file mode,
  the info dictionary contains the
  following structure: name: the
  filename of the directory in which to
  store all the files.

I'm guessing you could use

```<code>pathList.add(path[path.length - 1]);
</code>```

irrespective if the File object is a file or a directory.

Body:
The next code is a part of jBitTorrent API for Java a bit modified by me:

            if (!torr.saveAs.matches(""))
                info.put("name", torr.saveAs);
            else
                info.put("name", "noDirSpec");
            ArrayList files = new ArrayList();
            for (int i = 0; i < torr.name.size(); i++) {
                SortedMap file = new TreeMap();
                file.put("length", (Integer) torr.length.get(i));
//                String[] path = ((String) torr.name.get(i)).split("\\");
                String[] path = ((String) torr.name.get(i)).split("/");
                File f = new File((String)(torr.name.get(i)));
                ArrayList pathList = new ArrayList(path.length);

            if(f.isFile())
            {
                pathList.add(path[path.length - 1]);
            }
            else if(f.isDirectory())
            {

//                    ???
                }

This is torrent file(s) generation. So the «String[] path» is commented because of «\\» doesn't match linux slashes and generate invalid paths. Specification for multiple files is:

For the case of the multi-file mode, the info dictionary contains the following structure:
name: the filename of the directory in which to store all the files. This is purely advisory. (string)
files: a list of dictionaries, one for each file. Each dictionary in this list contains the following keys:
length: length of the file in bytes (integer)
md5sum: (optional) a 32-character hexadecimal string corresponding to the MD5 sum of the file. This is not used by BitTorrent at all, but it is included by some programs for greater compatibility.
path: a list containing one or more string elements that together represent the path and filename. Each element in the list corresponds to either a directory name or (in the case of the final element) the filename. For example, a the file "dir1/dir2/file.ext" would consist of three string elements: "dir1", "dir2", and "file.ext". This is encoded as a bencoded list of strings such as l4:dir14:dir28:file.exte

And for single file is:

For the case of the single-file mode, the info dictionary contains the following structure:
name: the filename. This is purely advisory. (string)
length: length of the file in bytes (integer)
md5sum: (optional) a 32-character hexadecimal string corresponding to the MD5 sum of the file. This is not used by BitTorrent at all, but it is included by some programs for greater compatibility.

So if I will use the previous code for single file here will be generated this torrent:

And torrent files contains:

d8:announce0:10:created by18:jBittorrentAPI 1.04:infod6:lengthi1645522e4:name27:ppkBB3cker-free-20101212.7z12:piece lengthi102400e6:pieces340:(ѕн‘xІZUЙ
ЃКХЪйкжѕЫ››3УМ‹ЁWпЖћA‡  ѕ,т C;НлАтжѓњЧ0x‡Е  %РъEЬ™сЖ®6ЦоёSЌ1пж`.бй%»†Ґ0VЩ%“ѕђoђџ'hЃ7ЦЭjъ\!RОQ.lВЦрjяGЋХ®^zЏ
ЎЉSЖЕ|„1D”кCРк+бћJLХmЛF`Ы"ГљSЪv$Л
Оuњi€ЙxQee

Okay. But how I should generate torrent for directory? The problem is that in unmodified API will be generated files with full path from root. But I need something like this:

And the valid torrent file is:

d10:created by25:Transmission/2.05 (11488)13:creation datei1302559094e8:encoding5:UTF-84:infod5:filesld6:lengthi196126e4:pathl29:1231190375_bulldozer.jar.parteed6:lengthi937518e4:pathl13:FIFA_2009-RPL35:240x320-fifa-rpl-2009(eng).jar.parteed6:lengthi802555e4:pathl13:FIFA_2009-RPL31:fifa-09-rpl_176x220_en.jar.parteed6:lengthi985098e4:pathl13:FIFA_2009-RPL36:FIFA_2009-RPL_240x320_(rus).jar.parteed6:lengthi138534e4:pathl41:GAZilaMarshrutkaUbiyca[game-torrent.info]41:GAZila_Marshrutka_Ubiyca_176x208.jar.parteed6:lengthi175851e4:pathl41:GAZilaMarshrutkaUbiyca[game-torrent.info]41:GAZila_Marshrutka_Ubiyca_240x320.jar.parteed6:lengthi827473e4:pathl33:God of War 3D (240х320).jar.parteed6:lengthi295164e4:pathl26:Men_In_Black-Alien_Assault39:Men_In_Black-Alien_Assault_176.jar.parteed6:lengthi374046e4:pathl26:Men_In_Black-Alien_Assault39:Men_In_Black-Alien_Assault_240.jar.parteee4:name53:5 отличных игр для мобильника12:piece lengthi32768e6:pieces2900:�dSI�%|Q�§I�I��oQ�CI�a1R�{ۦ��

Body:
I recommend you use System.getProperty("file.separator") to create valid paths on all OS's instead of hardcoding it to the windows file separator (\)

I havent used this API, but looking at the following line..

For the case of the multi-file mode,
  the info dictionary contains the
  following structure: name: the
  filename of the directory in which to
  store all the files.

I'm guessing you could use

pathList.add(path[path.length - 1]);

irrespective if the File object is a file or a directory.


问:
500 Internal Server Error when using .htaccess with RewriteEngine
I am on the shared host Bounceweb and I am trying to add some rewrite rules to make my links look prettier.

One of these rules is to make the url: http://mysite.com/upload point to: http://mysite.com/upload.php. I have this in my .htaccess file:

```<code>RewriteEngine on
RewriteRule ^upload$ upload.php
</code>```

but all it's giving me is a 500 Internal Server Error. I looked at my logs and this comes up a lot:

```<code>[alert] [client 81.179.29.185] /home/minecraf/public_html/.htaccess: Invalid command '\xef\xbb\xbfRewriteEngine', perhaps misspelled or defined by a module not included in the server configuration
</code>```

Does this mean my host doesn't support .htaccess? Pretty lame if they don't. I've already tried changing the permissions of .htaccess to 777 and it doesn't help.

Thanks!

答:
Just save your .htaccess file with UTF-8 encoding (without BOM) and upload.
Recommended to use Notepad++. (in my case that helped).

atb

ContentLicense: CC BY-SA 2.5

Body:
I am on the shared host Bounceweb and I am trying to add some rewrite rules to make my links look prettier.

One of these rules is to make the url: http://mysite.com/upload point to: http://mysite.com/upload.php. I have this in my .htaccess file:

RewriteEngine on
RewriteRule ^upload$ upload.php

but all it's giving me is a 500 Internal Server Error. I looked at my logs and this comes up a lot:

[alert] [client 81.179.29.185] /home/minecraf/public_html/.htaccess: Invalid command '\xef\xbb\xbfRewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

Does this mean my host doesn't support .htaccess? Pretty lame if they don't. I've already tried changing the permissions of .htaccess to 777 and it doesn't help.

Thanks!


问:
Method for opening a new fragment
I have this method that starts a new activity and it works perfectly, but how would I write something similar for opening a fragment?

```<code>public void goToInformatica(View v) {
    Intent a = new Intent(this, i.class);
    startActivity(a);
</code>```

usecase;

I have this hamburgermenu that takes me to different fragments, but I want some onscreen buttons to take me to the same fragments. The ID's for the buttons in the menu and the buttons onscreen are the same but because I call the fragments form OnNavigationItemSelected this doesn't work for normal buttons outside of the menu.

答:
you can use below code

```<code>  protected void setFragment(Fragment fragment, String tag) {
        FragmentTransaction t = getFragmentManager().beginTransaction();
        t.replace(R.id.container_dashboard, fragment, tag);
        t.commit();
    }
</code>```

getSupportFragmentManager() if you are doing fragment transaction
  from activity

getFragmentManager() if you are doing fragment transaction within
  fragment

Title: Method for opening a new fragment

Body:
I have this method that starts a new activity and it works perfectly, but how would I write something similar for opening a fragment?

public void goToInformatica(View v) {
    Intent a = new Intent(this, i.class);
    startActivity(a);

usecase;

I have this hamburgermenu that takes me to different fragments, but I want some onscreen buttons to take me to the same fragments. The ID's for the buttons in the menu and the buttons onscreen are the same but because I call the fragments form OnNavigationItemSelected this doesn't work for normal buttons outside of the menu.

Body:
you can use below code

  protected void setFragment(Fragment fragment, String tag) {
        FragmentTransaction t = getFragmentManager().beginTransaction();
        t.replace(R.id.container_dashboard, fragment, tag);
        t.commit();
    }

getSupportFragmentManager() if you are doing fragment transaction
  from activity

getFragmentManager() if you are doing fragment transaction within
  fragment


问:
xButton.setAttribute is not a function error
I have a function which formats elements in a JSON file to a table.

The table works fine, but now I am trying to implement a button on another column which deletes the said element from the file.

But when I did, it comes up with the error:
Uncaught (in promise) TypeError: xButton.setAttribute is not a function

Here is my code:

   async function table() {

    let response = await fetch('/tasks', {
     method: "GET",
     headers: {
     'Content-Type': 'application/json'
     }
    });

    let jsonPayload = await response.json();

    var table = document.getElementById("tableBody");

    tableBody.innerHTML = "";

    for(var i = jsonPayload.length - 1; i > -1; i--) {
      var row = tableBody.insertRow(0);

       var firstColumn = row.insertCell(0);
       var secondColumn = row.insertCell(1);
       var thirdColumn = row.insertCell(2);
       var fourthColumn = row.insertCell(3);

       var xButton = '<button>x</button>';
       xButton.setAttribute("onclick", `deleteElement('${jsonPayload[i].id}')`);

     firstColumn.innerHTML = jsonPayload[i].id;
     secondColumn.innerHTML = jsonPayload[i].desc;

     thirdColumn.innerHTML = jsonPayload[i].importance;
     fourthColumn.innerHTML = xButton;

    }

   }```
</div>
</div>
</p>

<p>This is the code to delete an element
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>//function which deletes a task.
   function deleteElement() {

   //Variable id is the number submitted in the input form to Delete tasks
      var id = document.getElementById("deleteId").value;

   //This is the url that is fetched with the variable id which deletes the function using the code from the backend.
   var url = "/tasks/"+id;

   //isNan checks whether id is not a number
   if (isNaN(id)) {
    //If it is not a number the error message is displayed.
    alert("The value inputted must be a number!");
    //Returns out of the function without proceeding
    return;
   }

   //Fetches /tasks, with the DELETE method
   fetch(url, {
    method: 'DELETE',
    headers: {
     'Content-Type': 'application/json'
    }
   });

   //display(); Calls the display function at the end to display the tasks again without the deleted url.
   display();
   }</code>```

The main issue is with the xButton, any help is appreciated.

答:
```<code>var xButton = document.createElement("BUTTON");
xButton.innerHTML = "x";
xButton.setAttribute("onclick", `deleteElement('${jsonPayload[i].id}')`);

// then at the end, instead of "fourthColumn.innerHTML = xButton;" you should do this
fourthColumn.appendChild(xButton);
</code>```

Body:
I have a function which formats elements in a JSON file to a table.

The table works fine, but now I am trying to implement a button on another column which deletes the said element from the file.

But when I did, it comes up with the error:
Uncaught (in promise) TypeError: xButton.setAttribute is not a function

Here is my code:

   async function table() {

    let response = await fetch('/tasks', {
     method: "GET",
     headers: {
     'Content-Type': 'application/json'
     }
    });

    let jsonPayload = await response.json();

    var table = document.getElementById("tableBody");

    tableBody.innerHTML = "";

    for(var i = jsonPayload.length - 1; i > -1; i--) {
      var row = tableBody.insertRow(0);

       var firstColumn = row.insertCell(0);
       var secondColumn = row.insertCell(1);
       var thirdColumn = row.insertCell(2);
       var fourthColumn = row.insertCell(3);

       var xButton = '<button>x</button>';
       xButton.setAttribute("onclick", `deleteElement('${jsonPayload[i].id}')`);

     firstColumn.innerHTML = jsonPayload[i].id;
     secondColumn.innerHTML = jsonPayload[i].desc;

     thirdColumn.innerHTML = jsonPayload[i].importance;
     fourthColumn.innerHTML = xButton;

    }

   }

This is the code to delete an element

//function which deletes a task.
   function deleteElement() {

   //Variable id is the number submitted in the input form to Delete tasks
      var id = document.getElementById("deleteId").value;

   //This is the url that is fetched with the variable id which deletes the function using the code from the backend.
   var url = "/tasks/"+id;

   //isNan checks whether id is not a number
   if (isNaN(id)) {
    //If it is not a number the error message is displayed.
    alert("The value inputted must be a number!");
    //Returns out of the function without proceeding
    return;
   }

   //Fetches /tasks, with the DELETE method
   fetch(url, {
    method: 'DELETE',
    headers: {
     'Content-Type': 'application/json'
    }
   });

   //display(); Calls the display function at the end to display the tasks again without the deleted url.
   display();
   }

The main issue is with the xButton, any help is appreciated.


问:
How to construct an Interval in Python in Grasshopper
Using Grasshopper: If I pass a domain into a Python component, python sees it as an Interval. I can do operation on it, as below:

```<code>print x
x.Grow(x[0]-y)
x.Grow(x[1]+y)

print x
print type(x)
print dir(x)
</code>```

Which prints:

```<code>20.3596657850938,87.5596657850938
19.3596657850938,88.5596657850938
<type 'Interval'>
['CompareTo', 'EpsilonEquals', 'Equals', 'FromIntersection', 'FromUnion', 'GetHashCode', 'GetObjectData', 'GetType', 'Grow', 'IncludesInterval', 'IncludesParameter', 'IsDecreasing', 'IsIncreasing', 'IsSingleton', 'IsValid', 'Item', 'Length', 'MakeIncreasing', 'Max', 'MemberwiseClone', 'Mid', 'Min', 'NormalizedIntervalAt', 'NormalizedParameterAt', 'ParameterAt', 'ParameterIntervalAt', 'ReferenceEquals', 'Reverse', 'Swap', 'T0', 'T1', 'ToString', 'Unset', '__add__', '__class__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rsub__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__sub__', '__subclasshook__']
</code>```

However, I can't work out how to construct a new one. They seem very useful, and I'd like to use them more.

I've tried importing the interval module (Runtime error (ImportException): No module named interval). I've tried casting a list to an Interval: Interval([1,2]) → Runtime error (UnboundNameException): name 'Interval' is not defined.

I don't know if interval belongs to Python, Iron Python or grasshopper.

How do I make a new Interval?

答:
With some help, I ended up with:

```<code>print "x is sent in as a domain from the input to this function"
print x, type(x)
print x.GetType().FullName
print x.GetType().Assembly.Location

print "\nThere seem to be two types of intervals, Rhino and grasshopper. Now sure why you'd use a Grasshopper interval, but here it is anyway:"
import Grasshopper as gh
y = gh.Kernel.Types.GH_Interval()
print y, type(y)
print y.GetType().FullName
print y.GetType().Assembly.Location

print "\nTo make a Rhino interval get it from the Rhino.Geometry module"
import Rhino.Geometry.Interval as interval
z = interval(0,1)
print z, type(z)
print z.GetType().FullName
print z.GetType().Assembly.Location

print "\nz is the same as x:", z == x
</code>```

which gives:

```<code>x is sent in as a domain from the input to this function
0,1 <type 'Interval'>
Rhino.Geometry.Interval
C:\Program Files\Rhinoceros 5 (64-bit)\System\RhinoCommon.dll

There seem to be two types of intervals, Rhino and grasshopper. Now sure why you'd use a Grasshopper interval, but here it is anyway:
0.0 To 0.0 <type 'GH_Interval'>
Grasshopper.Kernel.Types.GH_Interval
C:\Program Files\Common Files\McNeel\Rhinoceros\5.0\Plug-ins\Grasshopper (b45a29b1-4343-4035-989e-044e8580d9cf)\0.9.76.0\Grasshopper.dll

To make a Rhino interval get it from the Rhino.Geometry module
0,1 <type 'Interval'>
Rhino.Geometry.Interval
C:\Program Files\Rhinoceros 5 (64-bit)\System\RhinoCommon.dll

z is the same as x: True
</code>```

If we unpack that: IronPython's type() function actually returns a PythonType wrapping the .NET type. .GetType() gets the .NET type directly. So type(x) gives <type 'Interval'> which isn't very helpful, wheras x.GetType().FullName gives Rhino.Geometry.Interval which tells me exaclty how to get to it.

This is covered in the Rhino docs here, and it has a bunch of useful properties and methods.

Body:
Using Grasshopper: If I pass a domain into a Python component, python sees it as an Interval. I can do operation on it, as below:

print x
x.Grow(x[0]-y)
x.Grow(x[1]+y)

print x
print type(x)
print dir(x)

Which prints:

20.3596657850938,87.5596657850938
19.3596657850938,88.5596657850938
<type 'Interval'>
['CompareTo', 'EpsilonEquals', 'Equals', 'FromIntersection', 'FromUnion', 'GetHashCode', 'GetObjectData', 'GetType', 'Grow', 'IncludesInterval', 'IncludesParameter', 'IsDecreasing', 'IsIncreasing', 'IsSingleton', 'IsValid', 'Item', 'Length', 'MakeIncreasing', 'Max', 'MemberwiseClone', 'Mid', 'Min', 'NormalizedIntervalAt', 'NormalizedParameterAt', 'ParameterAt', 'ParameterIntervalAt', 'ReferenceEquals', 'Reverse', 'Swap', 'T0', 'T1', 'ToString', 'Unset', '__add__', '__class__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rsub__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__sub__', '__subclasshook__']

However, I can't work out how to construct a new one. They seem very useful, and I'd like to use them more.

I've tried importing the interval module (Runtime error (ImportException): No module named interval). I've tried casting a list to an Interval: Interval([1,2]) → Runtime error (UnboundNameException): name 'Interval' is not defined.

I don't know if interval belongs to Python, Iron Python or grasshopper.

How do I make a new Interval?

Body:
With some help, I ended up with:

print "x is sent in as a domain from the input to this function"
print x, type(x)
print x.GetType().FullName
print x.GetType().Assembly.Location

print "\nThere seem to be two types of intervals, Rhino and grasshopper. Now sure why you'd use a Grasshopper interval, but here it is anyway:"
import Grasshopper as gh
y = gh.Kernel.Types.GH_Interval()
print y, type(y)
print y.GetType().FullName
print y.GetType().Assembly.Location

print "\nTo make a Rhino interval get it from the Rhino.Geometry module"
import Rhino.Geometry.Interval as interval
z = interval(0,1)
print z, type(z)
print z.GetType().FullName
print z.GetType().Assembly.Location

print "\nz is the same as x:", z == x

which gives:

x is sent in as a domain from the input to this function
0,1 <type 'Interval'>
Rhino.Geometry.Interval
C:\Program Files\Rhinoceros 5 (64-bit)\System\RhinoCommon.dll

There seem to be two types of intervals, Rhino and grasshopper. Now sure why you'd use a Grasshopper interval, but here it is anyway:
0.0 To 0.0 <type 'GH_Interval'>
Grasshopper.Kernel.Types.GH_Interval
C:\Program Files\Common Files\McNeel\Rhinoceros\5.0\Plug-ins\Grasshopper (b45a29b1-4343-4035-989e-044e8580d9cf)\0.9.76.0\Grasshopper.dll

To make a Rhino interval get it from the Rhino.Geometry module
0,1 <type 'Interval'>
Rhino.Geometry.Interval
C:\Program Files\Rhinoceros 5 (64-bit)\System\RhinoCommon.dll

z is the same as x: True

If we unpack that: IronPython's type() function actually returns a PythonType wrapping the .NET type. .GetType() gets the .NET type directly. So type(x) gives <type 'Interval'> which isn't very helpful, wheras x.GetType().FullName gives Rhino.Geometry.Interval which tells me exaclty how to get to it.

This is covered in the Rhino docs here, and it has a bunch of useful properties and methods.


问:
JSON to dict with JsonConvert
I am accessing data from an API call in JSON format. I'm trying to put it in a dict, so that I can access the data. This works perfect for simple JSON objects, but fails for nested objects with "Unexpected character encountered while parsing value: [. Path 'cluster_functions', line 1, position 539."

My JSON:

```<code>{
"id": "xxxxx",
"uuid": "xxxxx",
"cluster_incarnation_id": 151013752,
"cluster_functions": ["NDFS"],
"is_lts": true,
"num_nodes": 4,
"block_serials": ["17xxx"],
"ntp_servers": ["172.26.140.50", "ntp.xxx.be"],
"service_centers": [],
"http_proxies": [],
"rackable_units": [{
    "id": 23,
    "rackable_unit_uuid": "09f211d1-8fb4-xxxx-86e2-ce819xxxx29",
    "positions": ["1", "2", "3", "4"],
    "nodes": [6, 7, 8, 9]
}],
"public_keys": [],
"smtp_server": null,
"hypervisor_types": ["kKvm"],
"cluster_redundancy_state": {
    "current_redundancy_factor": 2,
    "desired_redundancy_factor": 2,
    "redundancy_status": {
        "kCassandraPrepareDone": true,
        "kZookeeperPrepareDone": true
    }
}
}
</code>```

The code:

```<code>using (StreamReader reader = new StreamReader(HttpResponseStream))
                    {
                        //Response.Code = 1;
                        string body = reader.ReadToEnd();
                        consoleoutput("REST: result" + body);

                        resultdict = JsonConvert.DeserializeObject<Dictionary<string, string>>(body);

                    }
</code>```

I am not sure how to continue. Should I parse line by line, and do another deserialize if the value isn't a string? But how do I do this if I don't know the format of the JSON upfront (and so the amount of levels).

Or is there a more efficient way to parse to a dict no matter the amount of layers?

Thanks

答:
Try:

```<code>using (StreamReader reader = new StreamReader(HttpResponseStream))
{
    //Response.Code = 1;
    string body = reader.ReadToEnd();
    consoleoutput("REST: result" + body);

    resultdict = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(body);
}
</code>```

Anyway you shouldn't approach like that.

You should make a class describing every possible property and work like this:

```<code>public class Entity { /* properties definitions... */ }
</code>```

And then

```<code>using (StreamReader reader = new StreamReader(HttpResponseStream))
{
    //Response.Code = 1;
    string body = reader.ReadToEnd();
    consoleoutput("REST: result" + body);

    List<Entity> entities = JsonConvert.DeserializeObject<Entity>(body).ToList();
}
</code>```

Title: JSON to dict with JsonConvert

Body:
I am accessing data from an API call in JSON format. I'm trying to put it in a dict, so that I can access the data. This works perfect for simple JSON objects, but fails for nested objects with "Unexpected character encountered while parsing value: [. Path 'cluster_functions', line 1, position 539."

My JSON:

{
"id": "xxxxx",
"uuid": "xxxxx",
"cluster_incarnation_id": 151013752,
"cluster_functions": ["NDFS"],
"is_lts": true,
"num_nodes": 4,
"block_serials": ["17xxx"],
"ntp_servers": ["172.26.140.50", "ntp.xxx.be"],
"service_centers": [],
"http_proxies": [],
"rackable_units": [{
    "id": 23,
    "rackable_unit_uuid": "09f211d1-8fb4-xxxx-86e2-ce819xxxx29",
    "positions": ["1", "2", "3", "4"],
    "nodes": [6, 7, 8, 9]
}],
"public_keys": [],
"smtp_server": null,
"hypervisor_types": ["kKvm"],
"cluster_redundancy_state": {
    "current_redundancy_factor": 2,
    "desired_redundancy_factor": 2,
    "redundancy_status": {
        "kCassandraPrepareDone": true,
        "kZookeeperPrepareDone": true
    }
}
}

The code:

using (StreamReader reader = new StreamReader(HttpResponseStream))
                    {
                        //Response.Code = 1;
                        string body = reader.ReadToEnd();
                        consoleoutput("REST: result" + body);

                        resultdict = JsonConvert.DeserializeObject<Dictionary<string, string>>(body);

                    }

I am not sure how to continue. Should I parse line by line, and do another deserialize if the value isn't a string? But how do I do this if I don't know the format of the JSON upfront (and so the amount of levels).

Or is there a more efficient way to parse to a dict no matter the amount of layers?

Thanks

Body:
Try:

using (StreamReader reader = new StreamReader(HttpResponseStream))
{
    //Response.Code = 1;
    string body = reader.ReadToEnd();
    consoleoutput("REST: result" + body);

    resultdict = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(body);
}

Anyway you shouldn't approach like that.

You should make a class describing every possible property and work like this:

public class Entity { /* properties definitions... */ }

And then

using (StreamReader reader = new StreamReader(HttpResponseStream))
{
    //Response.Code = 1;
    string body = reader.ReadToEnd();
    consoleoutput("REST: result" + body);

    List<Entity> entities = JsonConvert.DeserializeObject<Entity>(body).ToList();
}


答:
You need to use createElement to create a button, as currently it is just a string..

```<code>var xButton = document.createElement("button");
xButton.innerHTML = "x";
xButton.setAttribute("onclick", `deleteElement('${jsonPayload[i].id}')`);
</code>```

Title: xButton.setAttribute is not a function error

Body:
You need to use createElement to create a button, as currently it is just a string..

var xButton = document.createElement("button");
xButton.innerHTML = "x";
xButton.setAttribute("onclick", `deleteElement('${jsonPayload[i].id}')`);


问:
How to implode image file names into mysql database
I am uploading multiple images to my sql database but my implode method isn't working...</p>

```<code>if(isset($_POST['submit'])) {
    $id     = $_POST['id'];
    for($i = 0; $i < count($_FILES['file_upload']['name']); $i++){
      $filetmp  = $_FILES['file_upload']['tmp_name'][$i];
      $filename = basename($_FILES['file_upload']['name'][$i]);
      $filetype = $_FILES['file_upload']['type'][$i];
      $filepath = "../images/".$filename;
      move_uploaded_file($filetmp,$filepath);
    }
      $mainfiles = implode(", ", $filename);

      $sql  = "INSERT INTO pictures2 (";
      $sql .= "image, photograph_id";
      $sql .= ") VALUES ('";
      $sql .= $database->escape_character($mainfiles) ."', '";
      $sql .= $id ."')";
      $result = $database->query($sql);
        if($result){
        $session->message('<div class="success-msg">Pictures uploaded sucessfully.</div>');
        }

}
</code>```

答:
Made changes like this, I am considering $id is your photograph_id

```<code>if (isset($_POST['submit'])) {
    $id = $_POST['id'];
    for ($i = 0; $i < count($_FILES['file_upload']['name']); $i++) {
        $filetmp    = $_FILES['file_upload']['tmp_name'][$i];
        $filename[] = [$id, basename($_FILES['file_upload']['name'][$i])]; // here changes
        $filetype   = $_FILES['file_upload']['type'][$i];
        $filepath   = "../images/" . $filename;
        move_uploaded_file($filetmp, $filepath);
    }
    // I made changes at below code
    $valueStr = array_map(function ($item) {
        return "('" . implode("','", $item) . "'),"; // to convert into `,` separated values
    }, $filename);
    $mainfiles = rtrim(implode("", $valueStr), ','); // removing right training `,`

    $sql = "INSERT INTO pictures2 (";
    $sql .= "image, photograph_id";
    $sql .= ") VALUES ('";
    $sql .= $database->escape_character($mainfiles) . "', '";
    $sql .= $id . "')";
    $result = $database->query($sql);
    if ($result) {
        $session->message('<div class="success-msg">Pictures uploaded sucessfully.</div>');
    }

}
</code>```

Body:
I am uploading multiple images to my sql database but my implode method isn't working...

if(isset($_POST['submit'])) {
    $id     = $_POST['id'];
    for($i = 0; $i < count($_FILES['file_upload']['name']); $i++){
      $filetmp  = $_FILES['file_upload']['tmp_name'][$i];
      $filename = basename($_FILES['file_upload']['name'][$i]);
      $filetype = $_FILES['file_upload']['type'][$i];
      $filepath = "../images/".$filename;
      move_uploaded_file($filetmp,$filepath);
    }
      $mainfiles = implode(", ", $filename);

      $sql  = "INSERT INTO pictures2 (";
      $sql .= "image, photograph_id";
      $sql .= ") VALUES ('";
      $sql .= $database->escape_character($mainfiles) ."', '";
      $sql .= $id ."')";
      $result = $database->query($sql);
        if($result){
        $session->message('
Pictures uploaded sucessfully.
');
        }

}

Body:
Made changes like this, I am considering $id is your photograph_id

if (isset($_POST['submit'])) {
    $id = $_POST['id'];
    for ($i = 0; $i < count($_FILES['file_upload']['name']); $i++) {
        $filetmp    = $_FILES['file_upload']['tmp_name'][$i];
        $filename[] = [$id, basename($_FILES['file_upload']['name'][$i])]; // here changes
        $filetype   = $_FILES['file_upload']['type'][$i];
        $filepath   = "../images/" . $filename;
        move_uploaded_file($filetmp, $filepath);
    }
    // I made changes at below code
    $valueStr = array_map(function ($item) {
        return "('" . implode("','", $item) . "'),"; // to convert into `,` separated values
    }, $filename);
    $mainfiles = rtrim(implode("", $valueStr), ','); // removing right training `,`

    $sql = "INSERT INTO pictures2 (";
    $sql .= "image, photograph_id";
    $sql .= ") VALUES ('";
    $sql .= $database->escape_character($mainfiles) . "', '";
    $sql .= $id . "')";
    $result = $database->query($sql);
    if ($result) {
        $session->message('<div class="success-msg">Pictures uploaded sucessfully.</div>');
    }

}


问:
Search records having comma seperated values that contains any element from the given list
I have a domain class Schedule with a property 'days' holding comma separated values like '2,5,6,8,9'.

```<code>Class Schedule {
   String days
   ...
}

Schedule schedule1 = new Schedule(days :'2,5,6,8,9')
schedule1.save()

Schedule schedule2 = new Schedule(days :'1,5,9,13')
schedule2.save()
</code>```

I need to get the list of the schedules having any day from the given list say [2,8,11].

Output: [schedule1]

How do I write the criteria query or HQL for the same. We can prefix & suffix the days with comma like ',2,5,6,8,9,' if that helps.

Thanks,

答:
Hope you have a good reason for such denormalization - otherwise it would be better to save the list to a child table.

Otherwise, querying would be complicated. Like:

```<code>  def days = [2,8,11]
  // note to check for empty days
  Schedule.withCriteria {
    days.each { day ->
      or {
        like('username', "$day,%") // starts with "$day"
        like('username', "%,$day,%")
        like('username', "%,$day") // ends with "$day"
      }
    }
  }
</code>```

Body:
I have a domain class Schedule with a property 'days' holding comma separated values like '2,5,6,8,9'.

Class Schedule {
   String days
   ...
}

Schedule schedule1 = new Schedule(days :'2,5,6,8,9')
schedule1.save()

Schedule schedule2 = new Schedule(days :'1,5,9,13')
schedule2.save()

I need to get the list of the schedules having any day from the given list say [2,8,11].

Output: [schedule1]

How do I write the criteria query or HQL for the same. We can prefix & suffix the days with comma like ',2,5,6,8,9,' if that helps.

Thanks,

Body:
Hope you have a good reason for such denormalization - otherwise it would be better to save the list to a child table.

Otherwise, querying would be complicated. Like:

  def days = [2,8,11]
  // note to check for empty days
  Schedule.withCriteria {
    days.each { day ->
      or {
        like('username', "$day,%") // starts with "$day"
        like('username', "%,$day,%")
        like('username', "%,$day") // ends with "$day"
      }
    }
  }