问:
Async in mapDispatchToProps - wrapper to ensure everything dispatches before rendering
The result I want is my component to not render unless all the async function have dispatched. I'm using this as a wrapper to make sure everything has dispatched. I've tried two ways:

call everything in componentWillMount and use setState to set loaded = true. I can then render the component based on my state's loaded key.

```<code>ajax = async () => {
  try{
    const { dispatch } = this.props;
    dispatch(loadPack('ars'));
    dispatch(loadPack('acr'));
    await dispatch(loadProds());
    await dispatch(loadRepls());
    await dispatch(checkEligibile());
    }catch (e) { console.log(e)}
 }

 componentWillMount() {
   this.ajax().then(() => {
     this.setState({ loaded: true });
   });
 }

render() {
 const { loaded } = this.state;
 return loaded ? <Component/> : null;
}
</code>```

This gets the desired results, except I see this error:

ExceptionsManager.js:71 Warning: Can only update a mounted or mounting
  component. This usually means you called setState, replaceState, or
  forceUpdate on an unmounted component. This is a no-op.

I tried dispatching in mapDispatchToProps. Ideally loaded should return true and I should see this.props.loaded = true to load my component. However, I'm receiving a Promise and not the result.

I'm feeling stuck here and not sure what else to try. Any suggestions?

```<code>const loadAsync = async dispatch => {
  dispatch(loadPack('ars'));
  dispatch(loadPack('acr'));
  await dispatch(loadProds());
  await dispatch(loadRepls());
  await dispatch(checkEligibile());
  return true
 };

 export const mapDispatchToProps = dispatch => ({
   loaded: loadAsync(dispatch),
 });
</code>```

答:
Since you are using redux, you have a global redux state. So after all dispatch, dispatch one more action that toogle a reducer state to true which indicate that all the actions has been dispatched.

In component, use dispatchStateToProps method to convert reducer state into props and then use that prop to check weather all the actions has been dispatched or not. It should roughly look something like this

```<code>ajax = async () => {
  try{
    const { dispatch } = this.props;
    dispatch(loadPack('ars'));
    dispatch(loadPack('acr'));
    await dispatch(loadProds());
    await dispatch(loadRepls());
    await dispatch(checkEligibile());
    // Add one more action here
    await dispatch(everythingDispatched());
    }catch (e) { console.log(e)}
 }
</code>```

Then a reducer state that keep track of that

```<code>dispatchTrackerReducer.js
switch(action.type){
  case "everythingDispatched" :
       everythingDispatched: true
       break;
}
</code>```

Then in component use mapStateToProps  like this

```<code>render() {
 const { everythingDispatched } = this.props;
 return everythingDispatched ? <Component/> : null;
}

function mapStateToProps(state){
  return {
       everythingDispatched:state.dispatchTrackerReducer.everythingDispatche
  }
}
</code>```

Body:
The result I want is my component to not render unless all the async function have dispatched. I'm using this as a wrapper to make sure everything has dispatched. I've tried two ways:

call everything in componentWillMount and use setState to set loaded = true. I can then render the component based on my state's loaded key.

ajax = async () => {
  try{
    const { dispatch } = this.props;
    dispatch(loadPack('ars'));
    dispatch(loadPack('acr'));
    await dispatch(loadProds());
    await dispatch(loadRepls());
    await dispatch(checkEligibile());
    }catch (e) { console.log(e)}
 }

 componentWillMount() {
   this.ajax().then(() => {
     this.setState({ loaded: true });
   });
 }

render() {
 const { loaded } = this.state;
 return loaded ? <Component/> : null;
}

This gets the desired results, except I see this error:

ExceptionsManager.js:71 Warning: Can only update a mounted or mounting
  component. This usually means you called setState, replaceState, or
  forceUpdate on an unmounted component. This is a no-op.

I tried dispatching in mapDispatchToProps. Ideally loaded should return true and I should see this.props.loaded = true to load my component. However, I'm receiving a Promise and not the result.

I'm feeling stuck here and not sure what else to try. Any suggestions?

const loadAsync = async dispatch => {
  dispatch(loadPack('ars'));
  dispatch(loadPack('acr'));
  await dispatch(loadProds());
  await dispatch(loadRepls());
  await dispatch(checkEligibile());
  return true
 };

 export const mapDispatchToProps = dispatch => ({
   loaded: loadAsync(dispatch),
 });

Body:
Since you are using redux, you have a global redux state. So after all dispatch, dispatch one more action that toogle a reducer state to true which indicate that all the actions has been dispatched.

In component, use dispatchStateToProps method to convert reducer state into props and then use that prop to check weather all the actions has been dispatched or not. It should roughly look something like this

ajax = async () => {
  try{
    const { dispatch } = this.props;
    dispatch(loadPack('ars'));
    dispatch(loadPack('acr'));
    await dispatch(loadProds());
    await dispatch(loadRepls());
    await dispatch(checkEligibile());
    // Add one more action here
    await dispatch(everythingDispatched());
    }catch (e) { console.log(e)}
 }

Then a reducer state that keep track of that

dispatchTrackerReducer.js
switch(action.type){
  case "everythingDispatched" :
       everythingDispatched: true
       break;
}

Then in component use mapStateToProps  like this

render() {
 const { everythingDispatched } = this.props;
 return everythingDispatched ? <Component/> : null;
}

function mapStateToProps(state){
  return {
       everythingDispatched:state.dispatchTrackerReducer.everythingDispatche
  }
}


来源: stackexchange

问:
Hosting Font-Awesome file on local server
I am using DataTables and in order to use the icons for the pagination buttons I am using font-awesome. I downloaded the file and there are two files

1- font-awesome
2- font-awesome.min

Which one do I need to add in my css to get the Forward, Next Previous icons and do I need to add any other files with it.

Currently I linking font-awesome.min.css but I don't see the button icons in my pagination

Thanks

答:
Use font awesome CDN Link

```<code><link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
</code>```

If is not working still please update your html code

ContentLicense: CC BY-SA 3.0

Body:
Use font awesome CDN Link

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">

If is not working still please update your html code


问:
Different tab width for TabLayout
I'm using TabLayout & ViewPager.
I am trying to change the size of the Tab, like Whatsapp (camera icon).
The size of the three Tabs is equal, but the Tab of the camera is smaller.
In every attempt I make the size of the Tabs remains the same (equal across all tabs).
Thanks.

答:
You need to lower the weight of the LinearLayout of the corresponding tab.

```<code>LinearLayout layout = ((LinearLayout) ((LinearLayout) tabLayout.getChildAt(0)).getChildAt(YOUR_TAB_NUMBER));
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) layout.getLayoutParams();
layoutParams.weight = YOUR_WEIGHT; // e.g. 0.5f
layout.setLayoutParams(layoutParams);
</code>```

Hope that helps!

Title: Different tab width for TabLayout

Body:
You need to lower the weight of the LinearLayout of the corresponding tab.

LinearLayout layout = ((LinearLayout) ((LinearLayout) tabLayout.getChildAt(0)).getChildAt(YOUR_TAB_NUMBER));
LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) layout.getLayoutParams();
layoutParams.weight = YOUR_WEIGHT; // e.g. 0.5f
layout.setLayoutParams(layoutParams);

Hope that helps!


问:
Visual Studio 2010 script debugger doesn't work for me
I just installed VS 2010 Beta 2 and wanted to play with an ASP.NET MVC 2 project.  I simply added some script (alert('hello');) into the Home controller's index.aspx view, and I can see it executing.  When I try to set a breakpoint, however, it never gets hit.  I also tried to use the "debugger" keyword, and when I do, I get a disappointing "there is no source code available for the current location" message.  I also get this message when I try to independently attach to an IE process where my app is running.

What do I need to do to get a friendly script debugging experience?  (I have successfully used Firebug to debug this, but for some reason I prefer the VS debugger.)

Here are some details of my configuration:

I am launching my stuff in VS 2010 Beta 2.

IE8 version 8.0.7600.16385 is my default browser.

The "Disable script debugging (Internet Explorer)" advanced option is unchecked.

The "Disable script debugging (Other)" option is unchecked.

In my ASP.NET MVC 2 project's "web" properties tab, the ASP.NET debugger is checked.  All others are unchecked.

Visual Studio 2008 script debugging seems to work just fine.

答: When debugging on IE, VS seems to add a folder called 'Script Documents' to the Solution Explorer. Inside this folder there is another folder called 'Windows Internet Explorer', and inside of it I see all the loaded js scripts and the (compiled) HTML file currently being displayed on IE. Setting breakpoints on the script tags in this HTML file does work for me.</p>

ContentLicense: CC BY-SA 2.5


问:
ReactDom is not defined?
I am trying to write a basic program in reactjs

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>Hello React!</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react-dom.min.js"></script>
    <script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script>
</head>
<body>
    <div id="example"></div>
    <script type="text/babel">
        ReactDOM.render(
        <h1>Hello, world!</h1>,
        document.getElementById('example')
        );
    </script>
</body>
</html>
</code>```

The above program works fine. But when I move the content inside my script file to a separate app.jsx file it shows error that reactDom is not defined.

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>Hello React!</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react-dom.min.js"></script>
    <script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script>
</head>
<body>
    <div id="example"></div>
    <script type="text/babel" src="app.jsx">

    </script>
</body>
</html>
</code>```

and my app.jsx looks like:

```<code>ReactDom.render(
    <h1>Hello React!!!</h1>,
    document.getElementById('example')
)
</code>```

答:
Correct syntax is ReactDOM.render.

See example below:

ReactDOM.render(

Hello React!!!
,
    document.getElementById('example')
)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="example"></div></code>```

Title: ReactDom is not defined?

Body:
I am trying to write a basic program in reactjs

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>Hello React!</title>

The above program works fine. But when I move the content inside my script file to a separate app.jsx file it shows error that reactDom is not defined.

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>Hello React!</title>

and my app.jsx looks like:

ReactDom.render(

Hello React!!!
,
    document.getElementById('example')
)

Body:
Correct syntax is ReactDOM.render.

See example below:

ReactDOM.render(
    <h1>Hello React!!!</h1>,
    document.getElementById('example')
)

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>

<div id="example"></div>


问:
pass PHP variable to javascript value
I want to display my PHP variable to JavaScript value
Here is my PHP and javascript code.

```<code><?php
$text = "Rates are subject to change without prior notice";
?>
<script>
    $('#typewriter').typewriter({
        prefix : "*** ",
        text : ["Rates are subject to change without prior notice"],
        typeDelay : 50,
        waitingTime : 1500,
        blinkSpeed : 200
    });
</script>
</code>```

inside the text parameter i want to pass my PHP variable.

答:
You can do it by using the following code</p>

```<code>     <script>
          $('#typewriter').typewriter({
          prefix : "*** ",
          text : ["<?php echo $text;?>"],
          typeDelay : 50,
          waitingTime : 1500,
          blinkSpeed : 200
        });
     </script>
</code>```

Title: pass PHP variable to javascript value

Body:
I want to display my PHP variable to JavaScript value
Here is my PHP and javascript code.

<?php
$text = "Rates are subject to change without prior notice";
?>

inside the text parameter i want to pass my PHP variable.

Body:
You can do it by using the following code

     <script>
          $('#typewriter').typewriter({
          prefix : "*** ",
          text : ["<?php echo $text;?>"],
          typeDelay : 50,
          waitingTime : 1500,
          blinkSpeed : 200
        });
     </script>


问:
Smoothly change a JavaFX effect
Is it possible to smoothly change an effect in JavaFX?
I've tried a lot of options, but nothing works.

For example - Java:

```<code>void effectChange(Node node) {
    // Node Effect = ColorAdjust (0.0, 0.0, 0.0, 0.0)
    KeyValue keyValue = new KeyValue(node.effectProperty(), new ColorAdjust(-0.8, 0.0, 0.0, 0.0));
    KeyFrame keyFrame = new KeyFrame(Duration.seconds(2.0), keyValue);
    Timeline timeline = new Timeline(keyFrame);
    timeline.play();
}
</code>```

For example - Kotlin:

```<code>fun effectChange(node: Node) {
    // Node Effect = ColorAdjust (0.0, 0.0, 0.0, 0.0)
    val keyValue = KeyValue(node.effectProperty(), ColorAdjust(-0.8, 0.0, 0.0, 0.0))
    val keyFrame = KeyFrame(Duration.seconds(2.0), keyValue)
    val timeline = Timeline(keyFrame)
    timeline.play()
}
</code>```

答:
You are timelining wrong property. Instead of changing the effect you should change effect's property. Take a look at the next example:</p>

```<code>    Button btn = new Button("Say 'Hello World'");
    ColorAdjust effect = new ColorAdjust(0.0, 0.0, 0.0, 0.0);
    btn.setEffect(effect);
    btn.setOnAction((ActionEvent event) -> {
        KeyValue keyValue = new KeyValue(effect.hueProperty(), -0.8);
        KeyFrame keyFrame = new KeyFrame(Duration.seconds(2.0), keyValue);
        Timeline timeline = new Timeline(keyFrame);
        timeline.play();
    });
</code>```

Title: Smoothly change a JavaFX effect

Body:
Is it possible to smoothly change an effect in JavaFX?
I've tried a lot of options, but nothing works.

For example - Java:

void effectChange(Node node) {
    // Node Effect = ColorAdjust (0.0, 0.0, 0.0, 0.0)
    KeyValue keyValue = new KeyValue(node.effectProperty(), new ColorAdjust(-0.8, 0.0, 0.0, 0.0));
    KeyFrame keyFrame = new KeyFrame(Duration.seconds(2.0), keyValue);
    Timeline timeline = new Timeline(keyFrame);
    timeline.play();
}

For example - Kotlin:

fun effectChange(node: Node) {
    // Node Effect = ColorAdjust (0.0, 0.0, 0.0, 0.0)
    val keyValue = KeyValue(node.effectProperty(), ColorAdjust(-0.8, 0.0, 0.0, 0.0))
    val keyFrame = KeyFrame(Duration.seconds(2.0), keyValue)
    val timeline = Timeline(keyFrame)
    timeline.play()
}

Body:
You are timelining wrong property. Instead of changing the effect you should change effect's property. Take a look at the next example:

    Button btn = new Button("Say 'Hello World'");
    ColorAdjust effect = new ColorAdjust(0.0, 0.0, 0.0, 0.0);
    btn.setEffect(effect);
    btn.setOnAction((ActionEvent event) -> {
        KeyValue keyValue = new KeyValue(effect.hueProperty(), -0.8);
        KeyFrame keyFrame = new KeyFrame(Duration.seconds(2.0), keyValue);
        Timeline timeline = new Timeline(keyFrame);
        timeline.play();
    });


问:
How to assign (add) value to a undefined item in a json object
I have a external json file and I parse it in to local object,
Currently I know I can't push value into a object so I want to assign a value to them here is my code:

```<code>//I parse my JSON into object and name it data
var data = {
  ...
}
// I use this object as a database so I don't list it all out
var name = "title";
var content = "hello guys";
data[name] = content;
// I wish after this script the object will have one more item like
// {
//  ...
//  "title": "hello guys",
//  ...
//}
</code>```

But the vscode's console show the following error when I run the script

```<code>TypeError: Cannot set property 'title' of undefined
</code>```

If you can assign value to undefined object how can you add item in to object.

But if there is any way that can let me assign value to undefined item, I'll be very happy

Here is the full code if you need

```<code>var jsonfile = require('jsonfile')

var file = './test.json'
var data = jsonfile.readFileSync(file); //I'm very sure data isn't undefined
//console.log(data);
var name="title";
var content="hello guys";
data.post[name] = content;

jsonfile.writeFileSync(file, tmd, {spaces: 4});
</code>```

答:
currently data = undefined and you are trying to access a key in undefined that is why you are getting an error, you need to assign an empty object to data if it is undefined. you can do something like this:

```<code>var data = data || {};
var name = "title";
var content = "hello guys";
data[name] = content;
</code>```

Body:
I have a external json file and I parse it in to local object,
Currently I know I can't push value into a object so I want to assign a value to them here is my code:

//I parse my JSON into object and name it data
var data = {
  ...
}
// I use this object as a database so I don't list it all out
var name = "title";
var content = "hello guys";
data[name] = content;
// I wish after this script the object will have one more item like
// {
//  ...
//  "title": "hello guys",
//  ...
//}

But the vscode's console show the following error when I run the script

TypeError: Cannot set property 'title' of undefined

If you can assign value to undefined object how can you add item in to object.

But if there is any way that can let me assign value to undefined item, I'll be very happy

Here is the full code if you need

var jsonfile = require('jsonfile')

var file = './test.json'
var data = jsonfile.readFileSync(file); //I'm very sure data isn't undefined
//console.log(data);
var name="title";
var content="hello guys";
data.post[name] = content;

jsonfile.writeFileSync(file, tmd, {spaces: 4});

Body:
currently data = undefined and you are trying to access a key in undefined that is why you are getting an error, you need to assign an empty object to data if it is undefined. you can do something like this:

var data = data || {};
var name = "title";
var content = "hello guys";
data[name] = content;


问:
Cosine similarity vs Cosine distance
I have a set of documents as given in the example below.

```<code>doc1 = {'Science': 0, 'History': 0, 'Politics': 0.15,... 'Sports': 0}
doc2 = {'Science': 0.3, 'History': 0.5, 'Politics': 0.1,... 'Sports': 0}
</code>```

I clustered these documents using DBSCAN by using the aforementioned vectors (my vectors are mostly sparse vectors). I get to know that 'cosine similarity' is extremely efficient to compute for sparse vectors. However, according to the sklearn.DBSCAN fit documentation you should use a distance matrix as input to DBSCAN. Hence, I want to know if it is wrong if I used 'cosine similarity' instead of 'cosine distance'.

Please let me know what is the most suitable approach for my problem. Is it DBSCAN using cosine distance or DBSCAN using cosine similarity?

```<code># Fit DBSCAN using cosine distance
db = DBSCAN(min_samples=1, metric='precomputed').fit(pairwise_distances(feature_matrix, metric='cosine'))
</code>```

OR

```<code># Fit DBSCAN using cosine similarity
    db = DBSCAN(min_samples=1, metric='precomputed').fit(1-pairwise_distances(feature_matrix, metric='cosine'))
</code>```

答:
If you pass a distance matrix it will be O(n²).

If you pass the actual data, the code could use an index to make it faster than this. So I'd rather try metric="cosine".

DBSCAN can trivially be implemented with a similarity rather than a distance (c.f. Generalized DBSCAN). I believe I saw this supported in ELKI, but not in sklearn. In sklearn, you can use cosine_distance with aforementioned drawbacks.

Title: Cosine similarity vs Cosine distance

Body:
I have a set of documents as given in the example below.

doc1 = {'Science': 0, 'History': 0, 'Politics': 0.15,... 'Sports': 0}
doc2 = {'Science': 0.3, 'History': 0.5, 'Politics': 0.1,... 'Sports': 0}

I clustered these documents using DBSCAN by using the aforementioned vectors (my vectors are mostly sparse vectors). I get to know that 'cosine similarity' is extremely efficient to compute for sparse vectors. However, according to the sklearn.DBSCAN fit documentation you should use a distance matrix as input to DBSCAN. Hence, I want to know if it is wrong if I used 'cosine similarity' instead of 'cosine distance'.

Please let me know what is the most suitable approach for my problem. Is it DBSCAN using cosine distance or DBSCAN using cosine similarity?

# Fit DBSCAN using cosine distance
db = DBSCAN(min_samples=1, metric='precomputed').fit(pairwise_distances(feature_matrix, metric='cosine'))

OR

# Fit DBSCAN using cosine similarity
    db = DBSCAN(min_samples=1, metric='precomputed').fit(1-pairwise_distances(feature_matrix, metric='cosine'))


问:
query from two tables CAST
I have a query from two tables ...

The first table in which the goods are in the form of tree accounts ....

The second table in which the sale is linked to the first table.

For example, now I have the first table.

Question A sort query is required ..

I get the cars for their condition ... electronics for their condition

Of Table II.

With attachments, I want to create a query.

Database Script :

```<code>USE [To_Test]
GO
/****** Object:  Table [dbo].[Items]    Script Date: 11/10/1438 05:54:35 م ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Items](
    [Id_ItemS] [int] NOT NULL,
    [Name_ar] [nvarchar](50) NULL,
    [Number_Id] [int] NULL,
    [Basic] [bit] NULL,
 CONSTRAINT [PK_Items] PRIMARY KEY CLUSTERED
(
    [Id_ItemS] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Sell_items](
    [Id_Sell] [int] IDENTITY(1,1) NOT NULL,
    [Id_items] [int] NULL,
    [price] [money] NULL,
 CONSTRAINT [PK_Sell_items] PRIMARY KEY CLUSTERED
(
    [Id_Sell] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (1, N'Cars', NULL, 1)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (2, N'electronics', NULL, 1)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (3, N'Toyota', 1, 1)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (4, N'Nissan', 1, 1)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (5, N'Camry', 3, 1)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (6, N'2015', 5, 0)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (7, N'2016', 5, 0)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (8, N'2017', 5, 0)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (9, N'TV', 2, 1)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (10, N'LG', 9, 0)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (11, N'Samsung', 9, 0)
SET IDENTITY_INSERT [dbo].[Sell_items] ON

INSERT [dbo].[Sell_items] ([Id_Sell], [Id_items], [price]) VALUES (1, 11, 2500.0000)
INSERT [dbo].[Sell_items] ([Id_Sell], [Id_items], [price]) VALUES (2, 10, 2300.0000)
INSERT [dbo].[Sell_items] ([Id_Sell], [Id_items], [price]) VALUES (3, 6, 20000.0000)
INSERT [dbo].[Sell_items] ([Id_Sell], [Id_items], [price]) VALUES (4, 7, 270000.0000)
SET IDENTITY_INSERT [dbo].[Sell_items] OFF
ALTER TABLE [dbo].[Items]  WITH CHECK ADD  CONSTRAINT [FK_Items_Items1] FOREIGN KEY([Number_Id])
REFERENCES [dbo].[Items] ([Id_ItemS])
GO
ALTER TABLE [dbo].[Items] CHECK CONSTRAINT [FK_Items_Items1]
GO
ALTER TABLE [dbo].[Sell_items]  WITH CHECK ADD  CONSTRAINT [FK_Sell_items_Items] FOREIGN KEY([Id_items])
REFERENCES [dbo].[Items] ([Id_ItemS])
GO
ALTER TABLE [dbo].[Sell_items] CHECK CONSTRAINT [FK_Sell_items_Items]
GO
</code>```

view

```<code>WITH Recursive_CTE AS (
SELECT        Items.Id_ItemS, Items.Name_ar, Items.Number_Id, 1 AS RecursionLevel, CAST(Items.Id_ItemS AS varchar(100)) AS Hierarchy, Sell_items.Id_Sell
FROM            Items INNER JOIN
                         Sell_items ON Items.Id_ItemS = Sell_items.Id_items
WHERE        (Items.Id_ItemS = 1)
 UNION ALL
SELECT        Items.Id_ItemS, Items.Name_ar, Items.Number_Id, 1 AS RecursionLevel, CAST(Hierarchy + ':' + CAST(Items.Id_ItemS AS varchar(100)) AS varchar(100)) AS Hierarchy, Sell_items.Id_Sell
FROM            Recursive_CTE AS parent INNER JOIN
                         Items ON parent.Id_items = Items.Number_Id INNER JOIN
                         Sell_items ON Items.Id_ItemS = Sell_items.Id_items )
SELECT * FROM Recursive_CTE ORDER BY Hierarchy
</code>```

but The result is null

I wish to modify the query ?

The desired result
enter image description here

答:
Add the following 3 inserts to Sell_items and you'll get results...

```<code>INSERT dbo.Sell_items (Id_Sell, Id_items, price) VALUES (5, 1, 270000.0000);
INSERT dbo.Sell_items (Id_Sell, Id_items, price) VALUES (6, 3, 280000.0000);
INSERT dbo.Sell_items (Id_Sell, Id_items, price) VALUES (7, 4, 290000.0000);
</code>```

Also note that you aren't incriminating your RecursionLevel column. You'll want to add 1 to the previous value...

```<code>parent.RecursionLevel + 1 AS RecursionLevel,
</code>```

Title: query from two tables CAST

Body:
I have a query from two tables ...

The first table in which the goods are in the form of tree accounts ....

The second table in which the sale is linked to the first table.

For example, now I have the first table.

Question A sort query is required ..

I get the cars for their condition ... electronics for their condition

Of Table II.

With attachments, I want to create a query.

Database Script :

USE [To_Test]
GO
/****** Object:  Table [dbo].[Items]    Script Date: 11/10/1438 05:54:35 م ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Items](
    [Id_ItemS] [int] NOT NULL,
    [Name_ar] [nvarchar](50) NULL,
    [Number_Id] [int] NULL,
    [Basic] [bit] NULL,
 CONSTRAINT [PK_Items] PRIMARY KEY CLUSTERED
(
    [Id_ItemS] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Sell_items](
    [Id_Sell] [int] IDENTITY(1,1) NOT NULL,
    [Id_items] [int] NULL,
    [price] [money] NULL,
 CONSTRAINT [PK_Sell_items] PRIMARY KEY CLUSTERED
(
    [Id_Sell] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (1, N'Cars', NULL, 1)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (2, N'electronics', NULL, 1)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (3, N'Toyota', 1, 1)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (4, N'Nissan', 1, 1)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (5, N'Camry', 3, 1)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (6, N'2015', 5, 0)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (7, N'2016', 5, 0)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (8, N'2017', 5, 0)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (9, N'TV', 2, 1)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (10, N'LG', 9, 0)
INSERT [dbo].[Items] ([Id_ItemS], [Name_ar], [Number_Id], [Basic]) VALUES (11, N'Samsung', 9, 0)
SET IDENTITY_INSERT [dbo].[Sell_items] ON

INSERT [dbo].[Sell_items] ([Id_Sell], [Id_items], [price]) VALUES (1, 11, 2500.0000)
INSERT [dbo].[Sell_items] ([Id_Sell], [Id_items], [price]) VALUES (2, 10, 2300.0000)
INSERT [dbo].[Sell_items] ([Id_Sell], [Id_items], [price]) VALUES (3, 6, 20000.0000)
INSERT [dbo].[Sell_items] ([Id_Sell], [Id_items], [price]) VALUES (4, 7, 270000.0000)
SET IDENTITY_INSERT [dbo].[Sell_items] OFF
ALTER TABLE [dbo].[Items]  WITH CHECK ADD  CONSTRAINT [FK_Items_Items1] FOREIGN KEY([Number_Id])
REFERENCES [dbo].[Items] ([Id_ItemS])
GO
ALTER TABLE [dbo].[Items] CHECK CONSTRAINT [FK_Items_Items1]
GO
ALTER TABLE [dbo].[Sell_items]  WITH CHECK ADD  CONSTRAINT [FK_Sell_items_Items] FOREIGN KEY([Id_items])
REFERENCES [dbo].[Items] ([Id_ItemS])
GO
ALTER TABLE [dbo].[Sell_items] CHECK CONSTRAINT [FK_Sell_items_Items]
GO

view

WITH Recursive_CTE AS (
SELECT        Items.Id_ItemS, Items.Name_ar, Items.Number_Id, 1 AS RecursionLevel, CAST(Items.Id_ItemS AS varchar(100)) AS Hierarchy, Sell_items.Id_Sell
FROM            Items INNER JOIN
                         Sell_items ON Items.Id_ItemS = Sell_items.Id_items
WHERE        (Items.Id_ItemS = 1)
 UNION ALL
SELECT        Items.Id_ItemS, Items.Name_ar, Items.Number_Id, 1 AS RecursionLevel, CAST(Hierarchy + ':' + CAST(Items.Id_ItemS AS varchar(100)) AS varchar(100)) AS Hierarchy, Sell_items.Id_Sell
FROM            Recursive_CTE AS parent INNER JOIN
                         Items ON parent.Id_items = Items.Number_Id INNER JOIN
                         Sell_items ON Items.Id_ItemS = Sell_items.Id_items )
SELECT * FROM Recursive_CTE ORDER BY Hierarchy

but The result is null

I wish to modify the query ?

The desired result
enter image description here

Body:
Add the following 3 inserts to Sell_items and you'll get results...

INSERT dbo.Sell_items (Id_Sell, Id_items, price) VALUES (5, 1, 270000.0000);
INSERT dbo.Sell_items (Id_Sell, Id_items, price) VALUES (6, 3, 280000.0000);
INSERT dbo.Sell_items (Id_Sell, Id_items, price) VALUES (7, 4, 290000.0000);

Also note that you aren't incriminating your RecursionLevel column. You'll want to add 1 to the previous value...

parent.RecursionLevel + 1 AS RecursionLevel,


问:
Developing a RIA with Django - what technology stack?
I need to develop a web application with the following requirements:

Desktop like UI on the client side

Application deployment

Scalability (i.e. distributing the service on multiple servers)

What I thought of so far (as I love Python but haven't done much web development yet):

Django

Fabric (think I've read somewhere it's suited for this)

What I'm missing is:

How to create rich clients (probably need some javascript libraries for that)?

How to distribute the service?

答:
For RIA you need to use some client technology in your templates.

See at Dojo or ExtJs.
ExtJs docs have example of Web Desktop app, but this library is not free for commercial project. I like more Dojo, and it is free.


问:
Unable to install new relic on linux using tomcat server
I have created account on new relic and downloaded zip for new relic agent and uploaded to /etc directory in my linux machine(tomcat server).

As per documentations, I follow the following code

```<code>cd /etc/newrelic
java -jar newrelic.jar install
</code>```

But I am getting following error:

```<code>Dec 31, 2013 06:14:04 +0000 NewRelic 1 INFO: Agent is using Logback
***** ( ( o))  New Relic Java Agent Installer
***** Installing version 3.2.3 ...
Could not edit start script because:
 .:. Could not locate a Tomcat, Jetty, JBoss, JBoss7 or Glassfish instance in /etc
Try re-running the install command with the -s <AppServerRootDirectory> option or from    <AppServerRootDirectory>/newrelic.
If that doesn't work, locate and edit the start script manually.
No need to create New Relic configuration file because:
 .:. A config file already exists: /etc/newrelic/newrelic.yml
***** Install incomplete
***** Next steps:
For help completing the install, see https://newrelic.com/docs/java/new-relic-for-java
</code>```

Can anyone give me solution for this?

答: Before you do any of these steps, make sure that your new relic folder is in inside the folder of your server. That immediately fixed my problem.

Body:
I have created account on new relic and downloaded zip for new relic agent and uploaded to /etc directory in my linux machine(tomcat server).

As per documentations, I follow the following code

cd /etc/newrelic
java -jar newrelic.jar install

But I am getting following error:

Dec 31, 2013 06:14:04 +0000 NewRelic 1 INFO: Agent is using Logback
***** ( ( o))  New Relic Java Agent Installer
***** Installing version 3.2.3 ...
Could not edit start script because:
 .:. Could not locate a Tomcat, Jetty, JBoss, JBoss7 or Glassfish instance in /etc
Try re-running the install command with the -s <AppServerRootDirectory> option or from    <AppServerRootDirectory>/newrelic.
If that doesn't work, locate and edit the start script manually.
No need to create New Relic configuration file because:
 .:. A config file already exists: /etc/newrelic/newrelic.yml
***** Install incomplete
***** Next steps:
For help completing the install, see https://newrelic.com/docs/java/new-relic-for-java

Can anyone give me solution for this?


问:
kubernetes master api / remote access with kubectl without certificates
I want to access remotely to kubernetes , but I dont want to use certificates for this

here is the content of my config file

```<code>apiVersion: v1
clusters:
- cluster:
    certificate-authority: /etc/kubernetes/ssl/ca.pem
    server: https://172.16.1.9:8443
  name: default-cluster
- cluster:
    certificate-authority: /etc/kubernetes/ssl/ca.pem
    server: https://172.16.1.9:8443
  name: remote-server
contexts:
- context:
    cluster: remote-server
    user: myself
  name: bcmt
- context:
    cluster: default-cluster
    user: default-admin
  name: default-system
current-context: default-system
kind: Config
preferences: {}
users:
- name: default-admin
  user:
    client-certificate: /etc/kubernetes/ssl/kubelet.pem
    client-key: /etc/kubernetes/ssl/kubelet-key.pem
- name: myself
  user:
    password: secret
    username: admin
</code>```

when I use only password user name , I am not able to access.

I am not expert in kubernetes,  I guess that I must change something in the remote kubernetes configuration files but I don't know what.

please can you help me for this

答:
You need to configure the kube-apiserver: https://kubernetes.io/docs/admin/authentication/#static-password-file

For all apiserver options see https://kubernetes.io/docs/admin/kube-apiserver/

Body:
I want to access remotely to kubernetes , but I dont want to use certificates for this

here is the content of my config file

apiVersion: v1
clusters:
- cluster:
    certificate-authority: /etc/kubernetes/ssl/ca.pem
    server: https://172.16.1.9:8443
  name: default-cluster
- cluster:
    certificate-authority: /etc/kubernetes/ssl/ca.pem
    server: https://172.16.1.9:8443
  name: remote-server
contexts:
- context:
    cluster: remote-server
    user: myself
  name: bcmt
- context:
    cluster: default-cluster
    user: default-admin
  name: default-system
current-context: default-system
kind: Config
preferences: {}
users:
- name: default-admin
  user:
    client-certificate: /etc/kubernetes/ssl/kubelet.pem
    client-key: /etc/kubernetes/ssl/kubelet-key.pem
- name: myself
  user:
    password: secret
    username: admin

when I use only password user name , I am not able to access.

I am not expert in kubernetes,  I guess that I must change something in the remote kubernetes configuration files but I don't know what.

please can you help me for this


问:
WooCommerce programmatically deleting from cart
How do I programmatically remove an item from the Woocommerce cart using AJAX? I tried putting a function in my functions.php file and accessing that but nothing gets deleted. I tried hard-coding product 299 but it doesn't delete. Here's what I did:

functions.php

```<code>function remove_item_from_cart() {
    $cart = WC()->instance()->cart;
    $id = 299;
    $cart_id = $cart->generate_cart_id($id);
    $cart_item_id = $cart->find_product_in_cart($cart_id);

    if($cart_item_id){
       $cart->set_quantity($cart_item_id, 0);
    }
    return true;
}
</code>```

themes/mine/main.js

```<code>$.ajax({
    type: 'POST',
    dataType: 'text',
    url: "http://www.../wp/wp-content/themes/mine/functions.php",
    data: {
        action: 'remove_item_from_cart'
    },
    success: function( data ) {
        console.log(data);
    }
});
</code>```

答:
For WooCommerce 3.0+ you can do it using the built-in remove_cart_item() function</p>

```<code>function findCartItemKey($cartItems, $productId){
  foreach($cartItems as $cartKey => $item){
    $product = $item['data'];
    if($product->get_id() == $productId){
            return $cartKey;
    }
    return false;
  }
}

global $woocommerce;
$cartItemKey = findCartItemKey($woocommerce->cart->get_cart())
$woocommerce->cart->remove_cart_item($cartItemKey);
</code>```

Body:
How do I programmatically remove an item from the Woocommerce cart using AJAX? I tried putting a function in my functions.php file and accessing that but nothing gets deleted. I tried hard-coding product 299 but it doesn't delete. Here's what I did:

functions.php

function remove_item_from_cart() {
    $cart = WC()->instance()->cart;
    $id = 299;
    $cart_id = $cart->generate_cart_id($id);
    $cart_item_id = $cart->find_product_in_cart($cart_id);

    if($cart_item_id){
       $cart->set_quantity($cart_item_id, 0);
    }
    return true;
}

themes/mine/main.js

$.ajax({
    type: 'POST',
    dataType: 'text',
    url: "http://www.../wp/wp-content/themes/mine/functions.php",
    data: {
        action: 'remove_item_from_cart'
    },
    success: function( data ) {
        console.log(data);
    }
});

Body:
For WooCommerce 3.0+ you can do it using the built-in remove_cart_item() function

function findCartItemKey($cartItems, $productId){
  foreach($cartItems as $cartKey => $item){
    $product = $item['data'];
    if($product->get_id() == $productId){
            return $cartKey;
    }
    return false;
  }
}

global $woocommerce;
$cartItemKey = findCartItemKey($woocommerce->cart->get_cart())
$woocommerce->cart->remove_cart_item($cartItemKey);


问:
Javascript clone node is not copying all values from cloned to new object
```<code><div class="container">
  <select class="btn" name="item">
    <option>Alpha</option>
    <option>Beta</option>
    <option>Gamma</option>
    <option>Theta</option>
  </select>
  <input type="text" class="desc" name="desc">
</div>
</code>```

In this example, element selected by default in the "select" dropdown is "Alpha". I want to clone the complete node with values. If i select a different value in the dropdown and enter some text in the input box, and then clone the node, only the text box value is cloned. The value of "select" dropdown in the new object remains the default (Alpha).

Why is the behavior of cloning different for "select" vs "input"?

```<code>var parent = document.querySelector(".container");
var button = parent.querySelector(".btn");
var textbox = parent.querySelector(".desc");

  > textbox.value
  < "some random text"
  > button.value
  < "Gamma"

var cloned = parent.cloneNode(true);
var childButton = cloned.querySelector(".btn");
var childTextbox = cloned.querySelector(".desc");

  > childTextbox.value
  < "some random text"
  > childButton.value
  < "Alpha"
</code>```

答:
When you change a selection, the state of the selection is stored in browser and the cloned node will never include the state of object/ element which is changed and/or stored by browser.

But for input, it is stored as a value of the attribute value and get cloned.

To clone a node with selected value,

You should detect the change event and add a selected attribute to it.

That is, add an event listener for select for change event.

Then in the callback function, set the attribute selected to that object by using

```<code>selectElement.options[selectElement.selectedIndex].setAttribute("selected","");
</code>```

Run the snippet below.

Select any value from the list and type something in the text box and click clone button.

var parent = document.querySelector(".container");
var button = parent.querySelector(".btn");
var textbox = parent.querySelector(".desc");
console.log(button.value);
console.log(textbox.value);
function update(val){
  val.options[val.selectedIndex].setAttribute("selected","");

}

function clone(){
  var cloned = parent.cloneNode(true);
  document.querySelector(".container-2").appendChild(cloned);
  var childButton = cloned.querySelector(".btn");
  var childTextbox = cloned.querySelector(".desc");
  console.log(button.value);
  console.log(textbox.value);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <select class="btn" name="item" onchange="update(this);">
    <option>Alpha</option>
    <option>Beta</option>
    <option>Gamma</option>
    <option>Theta</option>
  </select>
  <input type="text" class="desc" name="desc">
</div>
<button onclick="clone();">Clone</button>
<div class="container-2"></div></code>```

Body:
  <select class="btn" name="item">
    <option>Alpha</option>
    <option>Beta</option>
    <option>Gamma</option>
    <option>Theta</option>
  </select>
  <input type="text" class="desc" name="desc">

In this example, element selected by default in the "select" dropdown is "Alpha". I want to clone the complete node with values. If i select a different value in the dropdown and enter some text in the input box, and then clone the node, only the text box value is cloned. The value of "select" dropdown in the new object remains the default (Alpha).

Why is the behavior of cloning different for "select" vs "input"?

var parent = document.querySelector(".container");
var button = parent.querySelector(".btn");
var textbox = parent.querySelector(".desc");

  > textbox.value
  < "some random text"
  > button.value
  < "Gamma"

var cloned = parent.cloneNode(true);
var childButton = cloned.querySelector(".btn");
var childTextbox = cloned.querySelector(".desc");

  > childTextbox.value
  < "some random text"
  > childButton.value
  < "Alpha"

Body:
When you change a selection, the state of the selection is stored in browser and the cloned node will never include the state of object/ element which is changed and/or stored by browser.

But for input, it is stored as a value of the attribute value and get cloned.

To clone a node with selected value,

You should detect the change event and add a selected attribute to it.

That is, add an event listener for select for change event.

Then in the callback function, set the attribute selected to that object by using

selectElement.options[selectElement.selectedIndex].setAttribute("selected","");

Run the snippet below.

Select any value from the list and type something in the text box and click clone button.

var parent = document.querySelector(".container");
var button = parent.querySelector(".btn");
var textbox = parent.querySelector(".desc");
console.log(button.value);
console.log(textbox.value);
function update(val){
  val.options[val.selectedIndex].setAttribute("selected","");

}

function clone(){
  var cloned = parent.cloneNode(true);
  document.querySelector(".container-2").appendChild(cloned);
  var childButton = cloned.querySelector(".btn");
  var childTextbox = cloned.querySelector(".desc");
  console.log(button.value);
  console.log(textbox.value);
}

<div class="container">
  <select class="btn" name="item" onchange="update(this);">
    <option>Alpha</option>
    <option>Beta</option>
    <option>Gamma</option>
    <option>Theta</option>
  </select>
  <input type="text" class="desc" name="desc">
</div>
<button onclick="clone();">Clone</button>
<div class="container-2"></div>


问:
Qml - Exchange date between c++ class and class created by QmlRegisterType
I have the following question regards qml object loaded with qml Loader (setSource("qmlObject.qml")).

In qmlObject.qml I have imported objectClass(.h/.cpp) created with qmlRegisterType, thus when I launch loader.setSource("qmlObject.qml") command an instance of objectClass(.h/.cpp) is created.

I have other main class named coreClass(.h/.cpp) and I should exchange data between objectClass(.h/.cpp) and coreClass(.h/.cpp).

What's the best practice to implement this feature in my simple qt application?

答:
There are two ways to do that:

on C++ level, since both your objects are C++ objects, you can skip using QML as an intermediator and communicate directly. Presumably your core class will be one for the whole application, so you can expose it as a static member pointer  to the core in your object class. Therefore all object class instances will have access to it.

on QML level, by exposing the core class to QML as a context property, or preferably as a singleton, because the latter is the most efficient way. Then you can use its properties, signals and slots (but not pure public C++ stuff) in the form of a defined functional interface.

The first approach will be much faster performance wise, and will use less memory, the downside is you will have to recompile the C++ code on every change.

The second approach will limit the interaction to what is visible in QML, which is properties, signals, slots, and functions that have been marked as invokable. It will be slower and use more memory, but on the upside you won't have to recompile, so prototyping is much more rapid.

Often such interactions will be GUI based, so the overhead will not really matter, as the user doesn't interact with the GUI thousands of times per second. If efficiency is key, you can prototype using the second approach and get things running faster, and when you are done simply port the code to the first solution.

It is also important to mention that when you do C++ to QML integration, the correct way would be to have the C++ stuff exposed to QML and use it from QML. You should never ever have to reach from C++ to arbitrary stuff in QML, this is an indication of wrong design.


问:
PHP Unable to do file operations file (fopen, fwrite, fclose)
I am facing an issue. This is what my script looks like:

```<code>$file = fopen("logs/log.php", "r+") or die("Kan bestand (1) niet openen bradda!");
$content = fread($file, filesize("logs/log.php"));
fclose($file);
$filee = fopen("logs/log.php", "r+") or die("Kan bestand (2) niet openen bradda!");
$newcontent = $content.'<br /><b>'.$userRow['userId'].'   -   '.$userRow['userName'].'     -     '.$search;
fwrite($filee, $newcontent) or die("Kan bestand (3) niet openen bradda!");
fclose($filee);
</code>```

My purpose is to create a log. Everytime a user searches for a key word, it must be logged in the file 'log.php'.
I am running on a VPS (Windows server), and as i understood from another person with PHP experience, told me the directory/path should be different. Because it is not a webhost.
If that is exactly true, i don't know. But i hope you guys can help me out with this issue.

答:
Follow below steps:
1) Create log folder in your website root directory.
2) Check your log folder read/write permission. (required permission 777)
3) Use a+ on the place of r+. Because in r+ file pointer starts at the beginning of the file and in a+ the existing data in file is preserved. File pointer starts at the end of the file. Creates a new file if the file doesn’t exist.</p>

Body:
I am facing an issue. This is what my script looks like:

$file = fopen("logs/log.php", "r+") or die("Kan bestand (1) niet openen bradda!");
$content = fread($file, filesize("logs/log.php"));
fclose($file);
$filee = fopen("logs/log.php", "r+") or die("Kan bestand (2) niet openen bradda!");
$newcontent = $content.'
'.$userRow['userId'].'   -   '.$userRow['userName'].'     -     '.$search;
fwrite($filee, $newcontent) or die("Kan bestand (3) niet openen bradda!");
fclose($filee);

My purpose is to create a log. Everytime a user searches for a key word, it must be logged in the file 'log.php'.
I am running on a VPS (Windows server), and as i understood from another person with PHP experience, told me the directory/path should be different. Because it is not a webhost.
If that is exactly true, i don't know. But i hope you guys can help me out with this issue.


问:
transform xml to xsl
I'm calling a web service, it is returning result in XML format. How do I convert returning XML into XSL and display that in web browser?</p>

答: XSL is a language for specifying the visual formatting of an XML document. You cannot extract XSL from XML.</p>

Title: transform xml to xsl


问:
Get ViewContainerRef from Component
i want to create nested component in angular 4

this is chooser component

```<code>import {InputComponent} from './input/input.component'
import {BlockComponent} from './block/block.component'

export const FormChooser = {
  Block: BlockComponent,
  Input: InputComponent
}
</code>```

this is component builder

```<code>const component = FormChooser[data.component]
const factory = this.Resolver.resolveComponentFactory(component)

const new_component = this.ViewContainerRef.createComponent(factory)
</code>```

How to get new_component ViewContainerRef ? so i can use code like this

```<code>const another_new_component = new_component.createComponent(factory) // as ViewContainerRef
</code>```

Thank you...

答:
You can inject ViewContainer in constructor of dynamic component

```<code>class BlockComponent {
  constructor(public vcRef: ViewContainerRef) {}
}

const factory = this.Resolver.resolveComponentFactory(BlockComponent)

const newComponentRef = this.ViewContainerRef.createComponent(factory);
const newComponentVcRef = newComponentRef.instance.vcRef;
</code>```

or use @ViewChild to get reference to ViewContainerRef

```<code> template: '<ng-container #ref></ng-container>'
})
class BlockComponent {
  @ViewChild('ref') vcRef: ViewContainerRef;
}

const factory = this.Resolver.resolveComponentFactory(BlockComponent )

const newComponentRef = this.ViewContainerRef.createComponent(factory);
const newComponentVcRef = newComponentRef.instance.vcRef;
</code>```

Title: Get ViewContainerRef from Component

Body:
i want to create nested component in angular 4

this is chooser component

import {InputComponent} from './input/input.component'
import {BlockComponent} from './block/block.component'

export const FormChooser = {
  Block: BlockComponent,
  Input: InputComponent
}

this is component builder

const component = FormChooser[data.component]
const factory = this.Resolver.resolveComponentFactory(component)

const new_component = this.ViewContainerRef.createComponent(factory)

How to get new_component ViewContainerRef ? so i can use code like this

const another_new_component = new_component.createComponent(factory) // as ViewContainerRef

Thank you...

Body:
You can inject ViewContainer in constructor of dynamic component

class BlockComponent {
  constructor(public vcRef: ViewContainerRef) {}
}

const factory = this.Resolver.resolveComponentFactory(BlockComponent)

const newComponentRef = this.ViewContainerRef.createComponent(factory);
const newComponentVcRef = newComponentRef.instance.vcRef;

or use @ViewChild to get reference to ViewContainerRef

 template: '<ng-container #ref></ng-container>'
})
class BlockComponent {
  @ViewChild('ref') vcRef: ViewContainerRef;
}

const factory = this.Resolver.resolveComponentFactory(BlockComponent )

const newComponentRef = this.ViewContainerRef.createComponent(factory);
const newComponentVcRef = newComponentRef.instance.vcRef;

ContentLicense: CC BY-SA 4.0


问:
How disable @DependsOn annotation in arquillian tests?
I try to test singleton that have annotation @DependsOn where i mark another singletons that must be initialized before. But in test i don't want to load them, because its a lot of useless classes for my test. For ex:

```<code>@Singleton
@DependsOn({"anotherSingleton1", "anotherSingleton2"...})
public class SomeSingleton {
... methods and logic...
}
</code>```

Here's example of test:

```<code>public class SomeSingletonIT extends Arquillian {

    @Mock SomeClassInSingleton;
    ... another mocks...

    @Inject
    @InjectMocks
    SomeSingleton instance;

    @BeforeClass
    public void initMocks() {
        mocks logic
    }

    @Deployment
    public static WebArchive createDeployment() {

        return ShrinkWrap.create(WebArchive.class, "test.war")
                .addClasses(
                        SomeSingleton.class
                        )
                .addAsLibraries(some Libs)
                .addAsWebInfResource(EmptyAsset.INSTANCE,"beans.xml");
    }

    @Test
    public void testGetProactiveSubjects() throws Exception {
        System.out.println("***----------------------------------***");
        assertNotNull(instance);
        ...some assertions...
        System.out.println("***----------------------------------***");
    }

}
</code>```

I got exception that arquillian doesn't see classes of singletons in annotation @DependsOn. But if i include them in test archive - i will have to include all theirs dependencies too. And mock some logic in them that inits in @PostConstruct's. So... How can I disable or mock @DependsOn?
I use arquillian with wildfly managed container.

答: One idea which comes to my mind would be to implement a test double - dummy object - which you would substitute in your test deployment rather than deploying real singletons. This would save you from adding tons of dependencies and execution overhead when deploying your archive under test.</p>

Body:
I try to test singleton that have annotation @DependsOn where i mark another singletons that must be initialized before. But in test i don't want to load them, because its a lot of useless classes for my test. For ex:

@Singleton
@DependsOn({"anotherSingleton1", "anotherSingleton2"...})
public class SomeSingleton {
... methods and logic...
}

Here's example of test:

public class SomeSingletonIT extends Arquillian {

    @Mock SomeClassInSingleton;
    ... another mocks...

    @Inject
    @InjectMocks
    SomeSingleton instance;

    @BeforeClass
    public void initMocks() {
        mocks logic
    }

    @Deployment
    public static WebArchive createDeployment() {

        return ShrinkWrap.create(WebArchive.class, "test.war")
                .addClasses(
                        SomeSingleton.class
                        )
                .addAsLibraries(some Libs)
                .addAsWebInfResource(EmptyAsset.INSTANCE,"beans.xml");
    }

    @Test
    public void testGetProactiveSubjects() throws Exception {
        System.out.println("***----------------------------------***");
        assertNotNull(instance);
        ...some assertions...
        System.out.println("***----------------------------------***");
    }

}

I got exception that arquillian doesn't see classes of singletons in annotation @DependsOn. But if i include them in test archive - i will have to include all theirs dependencies too. And mock some logic in them that inits in @PostConstruct's. So... How can I disable or mock @DependsOn?
I use arquillian with wildfly managed container.


问:
How to close Files.write
I am to attempting to create directory and write data into that file. I am trying to use java nio to write file for more efficiently. My doubt is how to close it after write it below is my code. Please advice me.

And is this correct way to create directory and write large data files [200 kb].

```<code>    java.nio.file.Path path = java.nio.file.Paths.get(filePath);

    try {
        if (!java.nio.file.Files.exists(path)) {
            java.nio.file.Files.createDirectories(path.getParent());
            path = java.nio.file.Files.createFile(path);
            path = java.nio.file.Files.write(path, data.getBytes());
        } else {
            java.nio.file.Files.write(path, data.getBytes("utf-8"),
                    java.nio.file.StandardOpenOption.CREATE, java.nio.file.StandardOpenOption.TRUNCATE_EXISTING);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
    }
</code>```

答:
Closing file

You do not have to close it as the write method itself ensurer's that file will be closed once last byte is written.

As per description of Files.write() method.

Writes bytes to a file. The options parameter specifies how the the
  file is created or opened. If no options are present then this method
  works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are
  present. In other words, it opens the file for writing, creating the
  file if it doesn't exist, or initially truncating an existing
  regular-file to a size of 0. All bytes in the byte array are written
  to the file. The method ensures that the file is closed when all bytes
  have been written (or an I/O error or other runtime exception is
  thrown). If an I/O error occurs then it may do so after the file has
  created or truncated, or after some bytes have been written to the
  file.

Correct way to create directory and write large data files.

It's fine as long as you handle all exception conditions.

Title: How to close Files.write

Body:
I am to attempting to create directory and write data into that file. I am trying to use java nio to write file for more efficiently. My doubt is how to close it after write it below is my code. Please advice me.

And is this correct way to create directory and write large data files [200 kb].

    java.nio.file.Path path = java.nio.file.Paths.get(filePath);

    try {
        if (!java.nio.file.Files.exists(path)) {
            java.nio.file.Files.createDirectories(path.getParent());
            path = java.nio.file.Files.createFile(path);
            path = java.nio.file.Files.write(path, data.getBytes());
        } else {
            java.nio.file.Files.write(path, data.getBytes("utf-8"),
                    java.nio.file.StandardOpenOption.CREATE, java.nio.file.StandardOpenOption.TRUNCATE_EXISTING);
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
    }


问:
C++: creating .exe file from a .jar file or creating .jar launcher - .exe file
It would like to know how to create - I mean C++ example - .exe file from .jar file?
Do not want to use Launch4j or similar. Just want to do it from scratch.</p>

答:
#include
void main(void)
{
system("Java < Filename>");

Save as call center.c
properties:compile->make as .exe
Take the exe file from tc/bin


问:
in this i had 2 tables i need oldvalues in one row and newvalues in one row
Table1

create table emp(id int,emp_id int,
      name varchar(30),email varchar(50),mobile_no int,comments varchar(50));

table2

create table history(id int,oldvalue varchar(50),newvalue
  varchar(50));

inserting into 1st table

```<code>insert into emp(emp_id,name,email,mobile_no,comments)
 values(1, 'gobi','gobinath@gmail.com',9944,'good');
</code>```

TRIGGER

CREATE TRIGGER tri

```<code>BEFORE UPDATE ON emp

FOR EACH ROW

BEGIN

    INSERT INTO history

    SET id = '1',
     oldvalue = OLD.name,
     newvalue = NEW.name;
     INSERT INTO history

     SET id = '2',
      oldvalue = OLD.email,
     newvalue = NEW.email;
     INSERT INTO history

     SET id = '3',
     oldvalue = OLD.mobile_no,
     newvalue = NEW.mobile_no;
        END;
</code>```

```<code>UPDATE emp

SET
    name = 'ashok',
 email = 'ashok@gmail.com',
mobile_no = '929292'
WHERE
    emp_id = 1;
</code>```

This above trigger is working fine but i need to fill in 2 rows, but output of this trigger is multiple rows creating.

答:
```<code>create table emp(id int auto_increment,emp_id int,
name varchar(30),email varchar(50),mobile_no int,comments varchar(50),primary key(id));

create table history(id int,oldvalue varchar(50),newvalue varchar(50));

insert into emp(emp_id,name,email,mobile_no,comments)
 values(1, 'gobi','gobinath@gmail.com',9944,'good');

CREATE TRIGGER tri
    AFTER UPDATE ON emp
    FOR EACH ROW
BEGIN

DECLARE ooldvalue TEXT DEFAULT '';
    DECLARE nnewvalue TEXT DEFAULT '';

IF((OLD.name!=NEW.name) OR (OLD.email!=NEW.email) OR (OLD.mobile_no!=NEW.mobile_no))THEN
SET ooldvalue = CONCAT(ooldvalue,'id=', OLD.id,',');

    END IF;

IF(OLD.name!=NEW.name) THEN
        SET ooldvalue=CONCAT(ooldvalue,'name=',OLD.name,',');
        SET nnewvalue = CONCAT(nnewvalue,'name=',NEW.name,',');
    END IF;

IF(OLD.email!=NEW.email) THEN
        SET ooldvalue=CONCAT(ooldvalue,'email=',OLD.email,',');
        SET nnewvalue = CONCAT(nnewvalue,'email=',NEW.email,',');
    END IF;

IF(OLD.mobile_no!=NEW.mobile_no) THEN
        SET ooldvalue=CONCAT(ooldvalue,'mobile_no=',OLD.mobile_no,',');
        SET nnewvalue = CONCAT(nnewvalue,'mobile_no=',NEW.mobile_no,',');
    END IF;

IF(ooldvalue!='' AND nnewvalue!='') THEN

        IF(ooldvalue!=nnewvalue)THEN
            SET ooldvalue = SUBSTRING(ooldvalue,1,CHAR_LENGTH(ooldvalue)-1);
            SET nnewvalue = SUBSTRING(nnewvalue,1,CHAR_LENGTH(nnewvalue)-1);
            INSERT INTO history(oldvalue,newvalue) values (ooldvalue,nnewvalue);
         END IF;
        END IF;
      END;
</code>```

select  * from emp

select  * from history

```<code>UPDATE emp
SET
    name = 'ashok', email = 'ashok@gmail.com',mobile_no = '929292'
where
    emp_id = 1;
</code>```

Body:
Table1

create table emp(id int,emp_id int,
      name varchar(30),email varchar(50),mobile_no int,comments varchar(50));

table2

create table history(id int,oldvalue varchar(50),newvalue
  varchar(50));

inserting into 1st table

insert into emp(emp_id,name,email,mobile_no,comments)
 values(1, 'gobi','gobinath@gmail.com',9944,'good');

TRIGGER

CREATE TRIGGER tri

BEFORE UPDATE ON emp

FOR EACH ROW

BEGIN

    INSERT INTO history

    SET id = '1',
     oldvalue = OLD.name,
     newvalue = NEW.name;
     INSERT INTO history

     SET id = '2',
      oldvalue = OLD.email,
     newvalue = NEW.email;
     INSERT INTO history

     SET id = '3',
     oldvalue = OLD.mobile_no,
     newvalue = NEW.mobile_no;
        END;

UPDATE emp

SET
    name = 'ashok',
 email = 'ashok@gmail.com',
mobile_no = '929292'
WHERE
    emp_id = 1;

This above trigger is working fine but i need to fill in 2 rows, but output of this trigger is multiple rows creating.

Body:
create table emp(id int auto_increment,emp_id int,
name varchar(30),email varchar(50),mobile_no int,comments varchar(50),primary key(id));

create table history(id int,oldvalue varchar(50),newvalue varchar(50));

insert into emp(emp_id,name,email,mobile_no,comments)
 values(1, 'gobi','gobinath@gmail.com',9944,'good');

CREATE TRIGGER tri
    AFTER UPDATE ON emp
    FOR EACH ROW
BEGIN

DECLARE ooldvalue TEXT DEFAULT '';
    DECLARE nnewvalue TEXT DEFAULT '';

IF((OLD.name!=NEW.name) OR (OLD.email!=NEW.email) OR (OLD.mobile_no!=NEW.mobile_no))THEN
SET ooldvalue = CONCAT(ooldvalue,'id=', OLD.id,',');

    END IF;

IF(OLD.name!=NEW.name) THEN
        SET ooldvalue=CONCAT(ooldvalue,'name=',OLD.name,',');
        SET nnewvalue = CONCAT(nnewvalue,'name=',NEW.name,',');
    END IF;

IF(OLD.email!=NEW.email) THEN
        SET ooldvalue=CONCAT(ooldvalue,'email=',OLD.email,',');
        SET nnewvalue = CONCAT(nnewvalue,'email=',NEW.email,',');
    END IF;

IF(OLD.mobile_no!=NEW.mobile_no) THEN
        SET ooldvalue=CONCAT(ooldvalue,'mobile_no=',OLD.mobile_no,',');
        SET nnewvalue = CONCAT(nnewvalue,'mobile_no=',NEW.mobile_no,',');
    END IF;

IF(ooldvalue!='' AND nnewvalue!='') THEN

        IF(ooldvalue!=nnewvalue)THEN
            SET ooldvalue = SUBSTRING(ooldvalue,1,CHAR_LENGTH(ooldvalue)-1);
            SET nnewvalue = SUBSTRING(nnewvalue,1,CHAR_LENGTH(nnewvalue)-1);
            INSERT INTO history(oldvalue,newvalue) values (ooldvalue,nnewvalue);
         END IF;
        END IF;
      END;

select  * from emp

select  * from history

UPDATE emp
SET
    name = 'ashok', email = 'ashok@gmail.com',mobile_no = '929292'
where
    emp_id = 1;


问:
NullPointerException for JMeterPluginsCMD
Running this command:
sh bin/JMeterPluginsCMD.sh --generate-csv aggregate-report.csv --input-jtl summary.jtl --plugin-type AggregateReport

Getting an exception:

```<code>2017-07-07T23:48:27,865 INFO  [main] org.apache.jmeter.util.JMeterUtils: Setting Locale to en_US
ERROR: java.lang.NullPointerException
*** Problem's technical details go below ***
Home directory was detected as: src/test/jmeter/lib
Exception in thread "main" java.lang.NullPointerException
    at kg.apc.jmeter.PluginsCMDWorker.initializeProperties(PluginsCMDWorker.java:118)
    at kg.apc.jmeter.PluginsCMDWorker.prepareJMeterEnv(PluginsCMDWorker.java:81)
    at kg.apc.jmeter.PluginsCMDWorker.<init>(PluginsCMDWorker.java:55)
    at kg.apc.cmdtools.ReporterTool.processParams(ReporterTool.java:64)
    at kg.apc.cmdtools.PluginsCMD.processParams(PluginsCMD.java:66)
    at kg.apc.cmdtools.PluginsCMD.processParams(PluginsCMD.java:22)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at kg.apc.cmd.UniversalRunner.main(UniversalRunner.java:105)
</code>```

I used to have a lot of different errors like Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/jorphan/logging/LoggingManager
or Exception in thread "main" java.lang.RuntimeException: java.lang.ClassNotFoundException: kg.apc.jmeter.vizualizers.AggregateReportGui
. And I was able to resolve those by adding needed .jar files.
But I totally don't understand how to fix this NullPointerException.

答: When you download you need to copy lib folder also to jmeter/lib</p>

Body:
Running this command:
sh bin/JMeterPluginsCMD.sh --generate-csv aggregate-report.csv --input-jtl summary.jtl --plugin-type AggregateReport

Getting an exception:

2017-07-07T23:48:27,865 INFO  [main] org.apache.jmeter.util.JMeterUtils: Setting Locale to en_US
ERROR: java.lang.NullPointerException
*** Problem's technical details go below ***
Home directory was detected as: src/test/jmeter/lib
Exception in thread "main" java.lang.NullPointerException
    at kg.apc.jmeter.PluginsCMDWorker.initializeProperties(PluginsCMDWorker.java:118)
    at kg.apc.jmeter.PluginsCMDWorker.prepareJMeterEnv(PluginsCMDWorker.java:81)
    at kg.apc.jmeter.PluginsCMDWorker.<init>(PluginsCMDWorker.java:55)
    at kg.apc.cmdtools.ReporterTool.processParams(ReporterTool.java:64)
    at kg.apc.cmdtools.PluginsCMD.processParams(PluginsCMD.java:66)
    at kg.apc.cmdtools.PluginsCMD.processParams(PluginsCMD.java:22)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at kg.apc.cmd.UniversalRunner.main(UniversalRunner.java:105)

I used to have a lot of different errors like Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/jorphan/logging/LoggingManager
or Exception in thread "main" java.lang.RuntimeException: java.lang.ClassNotFoundException: kg.apc.jmeter.vizualizers.AggregateReportGui
. And I was able to resolve those by adding needed .jar files.
But I totally don't understand how to fix this NullPointerException.


问:
Uploading file using $_FILES and PHP
Today I tried for the first time to upload files to my website, but it seems that it doesn't work. I hope someone can help me, and I hope my code is readable :)

The problem is when I choose file and SUBMIT form it is not accepted because $_FILES is NULL

```<code>if (move_uploaded_file($_FILES['obrazok']['tmp_name'], $uploadfile))
</code>```

UPDATED Error

```<code>Warning: move_uploaded_file(www_nekonomagic/res/img/anime/uploads/793392545Untitled.jpg): failed to open stream: No such file or directory in /home/gj020900/www_nekonomagic/admin/admin-nove-anime.php on line 107

Warning: move_uploaded_file(): Unable to move '/home/gj020900/tmp/php9izgwb' to 'www_nekonomagic/res/img/anime/uploads/793392545Untitled.jpg' in /home/gj020900/www_nekonomagic/admin/admin-nove-anime.php on line 107
</code>```

Shorted form:

```<code><form enctype="multipart/form-data" action="../admin/admin-nove-anime.php" method="post" role="form">
    <div class="form-group col-md-6">
        <!-- MAX_FILE_SIZE must precede the file input field -->
        <input type="hidden" name="MAX_FILE_SIZE" value="3145728" />
        <label for="obrazok" class=""> Obrázok anime (Max. 3MB):</label>
        <input type="file" name="obrazok" id="obrazok" class="form-control" required>
    </div>
    <div class="form-group col-md-12">
        <input type="submit" class="btn btn-success" name="pridaj_anime_submit" value="Pridať anime" style="width: 100%;">
    </div>
</form>
</code>```

PHP part:

```<code>if (isset($_POST['pridaj_anime_submit'])) {
    // skontroluje sa ci sa subor ulozil ak ano pokracuje ak nie napise chybu
    $uploaddir = '/www_nekonomagic/res/img/anime/uploads/';
    $uploadfile = $uploaddir . basename($_FILES['obrazok']['name']);
    if (move_uploaded_file($_FILES['obrazok']['tmp_name'], $uploadfile)) {
        // prva cast formy
        $nazov = mysqli_real_escape_string($connect_to_db, $_POST['nazov']);
        $rok = mysqli_real_escape_string($connect_to_db, $_POST['rok']);
        $pocet = mysqli_real_escape_string($connect_to_db, $_POST['pocet']);
        $preklad = mysqli_real_escape_string($connect_to_db, $_POST['preklad']);
        $stav = mysqli_real_escape_string($connect_to_db, $_POST['stav']);

        $sql_vloz_anime = "INSERT INTO anime (a_name, a_year, a_translated_min, a_translated_max, a_rate_min, a_rate_max, a_edit, a_condition)
                                  VALUES ('$nazov', '$rok', '0', '$pocet', '8', '10', '$preklad', '$stav')";
        mysqli_query($connect_to_db, $sql_vloz_anime);
        $sql_ziskaj_a_id_pridaneho_anime = "SELECT * FROM anime WHERE a_name = '$nazov'";
        $run_sql_ziskaj_a_id_pridaneho_anime = mysqli_query($connect_to_db, $sql_ziskaj_a_id_pridaneho_anime);
        $a_id_ziskane = "";

        while ($db_data = mysqli_fetch_assoc($run_sql_ziskaj_a_id_pridaneho_anime)) {
            $a_id_ziskane = $db_data['a_id'];
        }

        // druha cast formy
        $obrazok = mysqli_real_escape_string($connect_to_db, $uploaddir.$_FILES['obrazok']['name']);
        $zaciatok = mysqli_real_escape_string($connect_to_db, $_POST['zaciatok']);
        $koniec = mysqli_real_escape_string($connect_to_db, $_POST['koniec']);
        $cas = mysqli_real_escape_string($connect_to_db, $_POST['cas']);
        $akihabara = mysqli_real_escape_string($connect_to_db, $_POST['akihabara']);

        $sql_vloz_anime_info = "INSERT INTO anime_info (a_id, a_img, a_start, a_stop, a_time_ep, a_akihabara)
                                            VALUES ('$a_id_ziskane', '$obrazok', '$zaciatok', '$koniec', '$cas', '$akihabara')";
        mysqli_query($connect_to_db, $sql_vloz_anime_info);
    }
    else {
        echo "
            <div class=\"alert alert-success alert-info\" style=\"margin: 10px 0\">
                <a href=\"#\" class=\"close\" data-dismiss=\"alert\" aria-label=\"close\">×</a>
                <strong>POZOR!</strong> Súbor sa nepodarilo nahrať.
            </div>
        ";
    }
}
</code>```

答:
Change your upload directory path line to :

```<code>$uploaddir = '/www_nekonomagic/res/img/anime/uploads/';
</code>```

You forget to add a backslash to the end of uploads. Do change as above and check if file is being saved in directory. Thanks.

Try to check if temp file is uploaded or not as :

```<code>if(is_uploaded_file($_FILES['obrazok']['tmp_name'])) {
 echo "Temp file uploaded. \r\n";
} else {
 echo "Temp file is not uploaded. \r\n";
}
</code>```

Title: Uploading file using $_FILES and PHP

Body:
Today I tried for the first time to upload files to my website, but it seems that it doesn't work. I hope someone can help me, and I hope my code is readable :)

The problem is when I choose file and SUBMIT form it is not accepted because $_FILES is NULL

if (move_uploaded_file($_FILES['obrazok']['tmp_name'], $uploadfile))

UPDATED Error

Warning: move_uploaded_file(www_nekonomagic/res/img/anime/uploads/793392545Untitled.jpg): failed to open stream: No such file or directory in /home/gj020900/www_nekonomagic/admin/admin-nove-anime.php on line 107

Warning: move_uploaded_file(): Unable to move '/home/gj020900/tmp/php9izgwb' to 'www_nekonomagic/res/img/anime/uploads/793392545Untitled.jpg' in /home/gj020900/www_nekonomagic/admin/admin-nove-anime.php on line 107

Shorted form:

<form enctype="multipart/form-data" action="../admin/admin-nove-anime.php" method="post" role="form">

        <input type="hidden" name="MAX_FILE_SIZE" value="3145728" />
         Obrázok anime (Max. 3MB):
        <input type="file" name="obrazok" id="obrazok" class="form-control" required>

        <input type="submit" class="btn btn-success" name="pridaj_anime_submit" value="Pridať anime" style="width: 100%;">

</form>

PHP part:

if (isset($_POST['pridaj_anime_submit'])) {
    // skontroluje sa ci sa subor ulozil ak ano pokracuje ak nie napise chybu
    $uploaddir = '/www_nekonomagic/res/img/anime/uploads/';
    $uploadfile = $uploaddir . basename($_FILES['obrazok']['name']);
    if (move_uploaded_file($_FILES['obrazok']['tmp_name'], $uploadfile)) {
        // prva cast formy
        $nazov = mysqli_real_escape_string($connect_to_db, $_POST['nazov']);
        $rok = mysqli_real_escape_string($connect_to_db, $_POST['rok']);
        $pocet = mysqli_real_escape_string($connect_to_db, $_POST['pocet']);
        $preklad = mysqli_real_escape_string($connect_to_db, $_POST['preklad']);
        $stav = mysqli_real_escape_string($connect_to_db, $_POST['stav']);

        $sql_vloz_anime = "INSERT INTO anime (a_name, a_year, a_translated_min, a_translated_max, a_rate_min, a_rate_max, a_edit, a_condition)
                                  VALUES ('$nazov', '$rok', '0', '$pocet', '8', '10', '$preklad', '$stav')";
        mysqli_query($connect_to_db, $sql_vloz_anime);
        $sql_ziskaj_a_id_pridaneho_anime = "SELECT * FROM anime WHERE a_name = '$nazov'";
        $run_sql_ziskaj_a_id_pridaneho_anime = mysqli_query($connect_to_db, $sql_ziskaj_a_id_pridaneho_anime);
        $a_id_ziskane = "";

        while ($db_data = mysqli_fetch_assoc($run_sql_ziskaj_a_id_pridaneho_anime)) {
            $a_id_ziskane = $db_data['a_id'];
        }

        // druha cast formy
        $obrazok = mysqli_real_escape_string($connect_to_db, $uploaddir.$_FILES['obrazok']['name']);
        $zaciatok = mysqli_real_escape_string($connect_to_db, $_POST['zaciatok']);
        $koniec = mysqli_real_escape_string($connect_to_db, $_POST['koniec']);
        $cas = mysqli_real_escape_string($connect_to_db, $_POST['cas']);
        $akihabara = mysqli_real_escape_string($connect_to_db, $_POST['akihabara']);

        $sql_vloz_anime_info = "INSERT INTO anime_info (a_id, a_img, a_start, a_stop, a_time_ep, a_akihabara)
                                            VALUES ('$a_id_ziskane', '$obrazok', '$zaciatok', '$koniec', '$cas', '$akihabara')";
        mysqli_query($connect_to_db, $sql_vloz_anime_info);
    }
    else {
        echo "

                ×
                POZOR! Súbor sa nepodarilo nahrať.

        ";
    }
}

Body:
Change your upload directory path line to :

$uploaddir = '/www_nekonomagic/res/img/anime/uploads/';

You forget to add a backslash to the end of uploads. Do change as above and check if file is being saved in directory. Thanks.

Try to check if temp file is uploaded or not as :

if(is_uploaded_file($_FILES['obrazok']['tmp_name'])) {
 echo "Temp file uploaded. \r\n";
} else {
 echo "Temp file is not uploaded. \r\n";
}


问:
How to find all positions of the maximum value in a list?
I have a list:

```<code>a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50,
             35, 41, 49, 37, 19, 40, 41, 31]
</code>```

max element is 55 (two elements on position 9 and 12)

I need to find on which position(s) the maximum value is situated. Please, help.

答:
You can do it in various ways.

The old conventional way is,

```<code>maxIndexList = list() #this list will store indices of maximum values
maximumValue = max(a) #get maximum value of the list
length = len(a)       #calculate length of the array

for i in range(length): #loop through 0 to length-1 (because, 0 based indexing)
    if a[i]==maximumValue: #if any value of list a is equal to maximum value then store its index to maxIndexList
        maxIndexList.append(i)

print(maxIndexList) #finally print the list
</code>```

Another way without calculating the length of the list and storing maximum value to any variable,

```<code>maxIndexList = list()
index = 0 #variable to store index
for i in a: #iterate through the list (actually iterating through the value of list, not index )
    if i==max(a): #max(a) returns a maximum value of list.
        maxIndexList.append(index) #store the index of maximum value
index = index+1 #increment the index

print(maxIndexList)
</code>```

We can do it in Pythonic and smart way! Using list comprehension just in one line,

```<code>maxIndexList = [i for i,j in enumerate(a) if j==max(a)] #here,i=index and j = value of that index
</code>```

All my codes are in Python 3.

Body:
I have a list:

a = [32, 37, 28, 30, 37, 25, 27, 24, 35, 55, 23, 31, 55, 21, 40, 18, 50,
             35, 41, 49, 37, 19, 40, 41, 31]

max element is 55 (two elements on position 9 and 12)

I need to find on which position(s) the maximum value is situated. Please, help.

Body:
You can do it in various ways.

The old conventional way is,

maxIndexList = list() #this list will store indices of maximum values
maximumValue = max(a) #get maximum value of the list
length = len(a)       #calculate length of the array

for i in range(length): #loop through 0 to length-1 (because, 0 based indexing)
    if a[i]==maximumValue: #if any value of list a is equal to maximum value then store its index to maxIndexList
        maxIndexList.append(i)

print(maxIndexList) #finally print the list

Another way without calculating the length of the list and storing maximum value to any variable,

maxIndexList = list()
index = 0 #variable to store index
for i in a: #iterate through the list (actually iterating through the value of list, not index )
    if i==max(a): #max(a) returns a maximum value of list.
        maxIndexList.append(index) #store the index of maximum value
index = index+1 #increment the index

print(maxIndexList)

We can do it in Pythonic and smart way! Using list comprehension just in one line,

maxIndexList = [i for i,j in enumerate(a) if j==max(a)] #here,i=index and j = value of that index

All my codes are in Python 3.


问:
Solr OR query on a text field
How to perform a simple query on a text field with an OR condition? Something like name:ABC OR name:XYZ so the resulting set would contain only those docs where name is exactly "XYZ" or "ABC"
Dug tons of manuals, cannot figure this out.
I use Solr 5.5.0

Update: Upgraded to Solr 6.6.0, still cannot figure it out. Below are illustrations to demonstrate my issue:

This works:

This works too:

This still works:

But this does not! Omg why!?

答:
There are many ways to perform OR query. Below I have listed some of them. You can select any of it.

[Simple Query]

```<code>q=name:(XYZ OR ABC)
</code>```

[Lucene Query Parser]

```<code>q={!lucene q.op=OR df=name v="XYZ ABC"}
</code>```

Title: Solr OR query on a text field

Body:
There are many ways to perform OR query. Below I have listed some of them. You can select any of it.

[Simple Query]

q=name:(XYZ OR ABC)

[Lucene Query Parser]

q={!lucene q.op=OR df=name v="XYZ ABC"}


问:
Displaying data from other table in php while loop
I am trying to display options in select tag from another table while my
 first, while loop continues, this is what I have tried so far !!

```<code><?php
     $query="SELECT * FROM `customerdata` WHERE takenby='$_SESSION[username]'";
     $query_two="SELECT * FROM `vendordriver` WHERE vendoremail='$_SESSION[username]'";
     $run_two=$db->query($query_two);
     $run=$db->query($query);
     while ($row=$run->fetch_assoc()) {
       echo " <tr><td>$row[bookingid]</td>
       <td>$row[drivername]</td>
       <td>$row[cabtype]</td>
       <td>$row[carnumber]</td><td><select>";
  while ($row_two=$run_two->fetch_assoc()) {
    echo "<option>$row_two[drivername]</option>";
  }
echo" </select></td>
       <td><input type='submit' class='btn btn-success' value='SEND '>
       </td>";
     }
    ?>
</code>```

Any Suggestions Please !!!

答:
Define the result from the second query as an array variable then with in the first query loop with in that array to echo the drivers names here you execute second query before the first one

```<code>$query="SELECT * FROM `customerdata` WHERE     takenby='$_SESSION[username]'";
$query_two="SELECT * FROM `vendordriver` WHERE vendoremail='$_SESSION[username]'";
$if(!isset($array_option)){$array_option=array();}
$run_two=$db->query($query_two);
$run=$db->query($query);
while ($row_two=$run_two->fetch_assoc()) {
array_push($array_option,$row_two[driver_name];
}
</code>```

Then within looping through first query do this

```<code>while ($row=$run->fetch_assoc()) {
echo " <tr><td>$row[bookingid]</td>
<td>$row[drivername]</td>
<td>$row[cabtype]</td>
<td>$row[carnumber]</td><td><select>";
for($i=0;$i<count($array_option);$i++){
echo "<option>$array_option[$i]</option>"
}
</code>```

Then the rest of the code

```<code>echo" </select></td><td><input type='submit' class='btn btn-success' value='SEND '></td>";
}
?>
</code>```

Body:
I am trying to display options in select tag from another table while my
 first, while loop continues, this is what I have tried so far !!

<?php
     $query="SELECT * FROM `customerdata` WHERE takenby='$_SESSION[username]'";
     $query_two="SELECT * FROM `vendordriver` WHERE vendoremail='$_SESSION[username]'";
     $run_two=$db->query($query_two);
     $run=$db->query($query);
     while ($row=$run->fetch_assoc()) {
       echo "
$row[bookingid]
       $row[drivername]
       $row[cabtype]
       $row[carnumber]	<select>";
  while ($row_two=$run_two->fetch_assoc()) {
    echo "<option>$row_two[drivername]</option>";
  }
echo" </select>
       <input type='submit' class='btn btn-success' value='SEND '>
       	";
     }
    ?>

Any Suggestions Please !!!

Body:
Define the result from the second query as an array variable then with in the first query loop with in that array to echo the drivers names here you execute second query before the first one

$query="SELECT * FROM `customerdata` WHERE     takenby='$_SESSION[username]'";
$query_two="SELECT * FROM `vendordriver` WHERE vendoremail='$_SESSION[username]'";
$if(!isset($array_option)){$array_option=array();}
$run_two=$db->query($query_two);
$run=$db->query($query);
while ($row_two=$run_two->fetch_assoc()) {
array_push($array_option,$row_two[driver_name];
}

Then within looping through first query do this

while ($row=$run->fetch_assoc()) {
echo " <tr><td>$row[bookingid]</td>
<td>$row[drivername]</td>
<td>$row[cabtype]</td>
<td>$row[carnumber]</td><td><select>";
for($i=0;$i<count($array_option);$i++){
echo "<option>$array_option[$i]</option>"
}

Then the rest of the code

echo" </select></td><td><input type='submit' class='btn btn-success' value='SEND '></td>";
}
?>


问:
How to copy the hidden field value and pass it on another page using jquery in CodeIgniter?
I am new with CodeIgniter and I want to pass hidden field value to another page using jQuery in CodeIgniter. Can I do this using jQuery?

```<code><input type="hidden" name="grdtot" class="grdtot" />
</code>```

this hidden field on cart.php page

```<code>  <label id="grdtot_c" name="grdtot_c" class="grdtot_c"></label>
</code>```

I want to fetch this hidden field value on checkout.php page. How I can do this using jQuery?

答:
You can do this another way using localstorage to getting value from another page

Just write like this on page one.

```<code>localStorage.setItem('Gridtotal', $('.grdtot').val());
</code>```

And get value from another page.

```<code>var grdTotal= localStorage.getItem('Gridtotal');
$('#grdtot_c').val(grdTotal);
</code>```

Body:
I am new with CodeIgniter and I want to pass hidden field value to another page using jQuery in CodeIgniter. Can I do this using jQuery?

<input type="hidden" name="grdtot" class="grdtot" />

this hidden field on cart.php page

I want to fetch this hidden field value on checkout.php page. How I can do this using jQuery?

Body:
You can do this another way using localstorage to getting value from another page

Just write like this on page one.

localStorage.setItem('Gridtotal', $('.grdtot').val());

And get value from another page.

var grdTotal= localStorage.getItem('Gridtotal');
$('#grdtot_c').val(grdTotal);


问:
"Fallthrough" in Django URLConf?
I've got a situation where I'm basically allowing any URL, with no prefix; one way that I had been thinking of designing it involved basically having two '' matches - the first would see if it could serve the request and if not it would fall through to the second.

If I raise Http404 from the first view, I get a 404 page.

If I return, I get a ValueError complaining I "didn't return an HttpResponse object."

Looking briefly at the code in django.core.urlresolvers, I'm fairly convinced that the architecture simply isn't in place to do this - it resolves to a single match, the URL resolution phase is entirely separate from the view phase and once you've gone to the view there's no returning to the URL resolution phase. Is this correct? Personally I would see this as a slight deficiency; I can see how it could be quite useful to have two types of 404 - one saying "no, it doesn't exist" as it currently does, and one saying "I don't know about it", which would make it look through further the URLConf. At the moment it seems to me like anyone wanting this style of system basically has to replace the URL resolution part of Django.

I've worked around this (basically getting a trivial view to palm it off to one and then the other), so I don't think I really have any need for this particular thing any more, but still I'm curious if there is a way of doing this which I just didn't spot, or whether there might be a neater workaround.

答:
I don't know why you have two views here. Surely you really only have one view, which can do two (or more) things. Change your view function to something like:

```<code> if canDoMethod1(request):
    doMethod1(request)
 else:
    doMethod2(request)
</code>```

or whatever. That gets triggered on any URL. Sorted.

Title: "Fallthrough" in Django URLConf?

Body:
I don't know why you have two views here. Surely you really only have one view, which can do two (or more) things. Change your view function to something like:

 if canDoMethod1(request):
    doMethod1(request)
 else:
    doMethod2(request)

or whatever. That gets triggered on any URL. Sorted.


问:
Is it possible to write soap web services using .net core?
I have been tasked to explore if its possible to write soap services on .net core. It seems like there is a test version of WCF for consuming. But i have not been able to find much abt producing soap web services. Is it possible?</p>

答:
So the WCF client libraries have been ported to .net core but the server side libraries haven't as of the time of writing. There is this long running issue which is a request for the server side libraries to be ported over and Microsoft are saying it will happen, see this from a few weeks ago:

WCF for .NET Core is very much on our radar, and we are working with the ASP.NET Core to prioritize this work. We will share more details when they are available to broadcast publicly.

Of course you don't need WCF necessarily to do SOAP but I guess that's what you were asking. A quick search gives this repo and I guess the are probably others but WCF isn't there yet.


问:
"Ambiguous reference to member 'count' " Error
I'm not that much of a pro in using swift..but i've been trying to create an social media app using firebase as backend. But I am stuck in this one part where the data gets stored in an Array..but when . i call the array I keep getting the "Ambiguous reference to member 'count' " error and I have tried many ways to fix this but end up unsuccessful every time

```<code>var posts = [AnyObject?]()

override func viewDidLoad() {
    super.viewDidLoad()

 }

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell: HomeViewTableViewCell = tableView.dequeueReusableCell(withIdentifier: "HomeViewTableViewCell", for: indexPath) as! HomeViewTableViewCell

    let post = (posts[(self.posts.count - 1) - indexPath.row] as AnyObject).value["text"] as! String  //**Ambiguous reference to member 'count'

    cell.configure(nil,NameText:self.loggedInUserData!.value["NameText"] as! String, TitleText:self.loggedInUserData!.value["TitleText"] as! String, post:post)

    return cell
}
</code>```

Please help!

Actually trying this tutorial out in Youtube...So if full code required, This is the YouTube link:

https://www.youtube.com/watch?v=BeZ3i7-gaok&list=PLy9JCsy2u97kro0jXbXrPFmT-DQVAmNW0&index=4

答:
you might want to use value(forKey:) here</p>

```<code>let post = (posts[(self.posts.count - 1) - indexPath.row] as AnyObject).value(forKey: "text")
</code>```

Body:
I'm not that much of a pro in using swift..but i've been trying to create an social media app using firebase as backend. But I am stuck in this one part where the data gets stored in an Array..but when . i call the array I keep getting the "Ambiguous reference to member 'count' " error and I have tried many ways to fix this but end up unsuccessful every time

var posts = [AnyObject?]()

override func viewDidLoad() {
    super.viewDidLoad()

 }

 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell: HomeViewTableViewCell = tableView.dequeueReusableCell(withIdentifier: "HomeViewTableViewCell", for: indexPath) as! HomeViewTableViewCell

    let post = (posts[(self.posts.count - 1) - indexPath.row] as AnyObject).value["text"] as! String  //**Ambiguous reference to member 'count'

    cell.configure(nil,NameText:self.loggedInUserData!.value["NameText"] as! String, TitleText:self.loggedInUserData!.value["TitleText"] as! String, post:post)

    return cell
}

Please help!

Actually trying this tutorial out in Youtube...So if full code required, This is the YouTube link:

https://www.youtube.com/watch?v=BeZ3i7-gaok&list=PLy9JCsy2u97kro0jXbXrPFmT-DQVAmNW0&index=4

Body:
you might want to use value(forKey:) here

let post = (posts[(self.posts.count - 1) - indexPath.row] as AnyObject).value(forKey: "text")


问:
Azure Service Bus: How to publish more than 256KB message to a Topic?
I am old school Windows Azure Architect. Using service bus topics to pass messages to worker role.

How to publish more thank 256KB message to a subscription? I know
  there is a premium tier service bus which allows 1MB message, but
  1MB limit will may also not be enough.

答:
If you're trying to send a message that is more than 256KB/1MB and avoid claim check pattern, then I'm questioning the design. ASB is about messaging, not data transfer.

The current ASB client (WindowsAzure.ServiceBus) doesn't make claim check pattern implementation trivial, indeed. The good news is that with the new client (Microsoft.Azure.ServiceBus) it's much simpler. You can leverage Extensions API and either use claim check pattern implementation provided by ServiceBus.AttachmentPlugin or extend it and allow multiple Storage accounts to be leveraged.


问:
Kivy Python- Text Input Box Filling Entire Float Layout Screen
I am running into an issue with TextInput in Kivy.

When I add it to the existing FloatLayout on one of my screens it takes up the entire window, even with a height specified. I'd like to keep this in the .py file, so please refrain from adding any styling options for sizing in a .kv file.

```<code>class WebsiteInput(Screen):
    def __init__(self, **kwargs):
        super(WebsiteInput, self).__init__(**kwargs)
        Clock.schedule_once(self._finish_init)

    def _finish_init(self, dt):
        # Title Label
        self.lbl1 = Label(text="Enter a URL to bind to this button:", pos=(self.x, self.height +132))
        self.lbl1.font_name = 'Montserrat-Bold.ttf'
        self.lbl1.font_size = 28
        self.ids.float_web.add_widget(self.lbl1)
        # URL Text Input
        self.web_input = TextInput(height=100)
        self.web_input.height = 100
        self.ids.float_web.add_widget(self.web_input)
</code>```

As you can see I have tried affecting the size in two different locations, and it is still filling the entire window.

答:
For the size property to take effect you need the size_hint property to be None on the corresponding axis:

```<code>class WebsiteInput(Screen):
    def __init__(self, **kwargs):
        super(WebsiteInput, self).__init__(**kwargs)
        Clock.schedule_once(self._finish_init)

    def _finish_init(self, dt):
        # Title Label
        self.lbl1 = Label(text="Enter a URL to bind to this button:",
                          pos=(self.x, self.height +132))
        self.lbl1.font_name = 'Montserrat-Bold.ttf'
        self.lbl1.font_size = 28
        self.ids.float_web.add_widget(self.lbl1)
        # URL Text Input
        self.web_input = TextInput(height=100,
                                   size_hint = (1,  None))
        self.ids.float_web.add_widget(self.web_input)
</code>```

Body:
I am running into an issue with TextInput in Kivy.

When I add it to the existing FloatLayout on one of my screens it takes up the entire window, even with a height specified. I'd like to keep this in the .py file, so please refrain from adding any styling options for sizing in a .kv file.

class WebsiteInput(Screen):
    def __init__(self, **kwargs):
        super(WebsiteInput, self).__init__(**kwargs)
        Clock.schedule_once(self._finish_init)

    def _finish_init(self, dt):
        # Title Label
        self.lbl1 = Label(text="Enter a URL to bind to this button:", pos=(self.x, self.height +132))
        self.lbl1.font_name = 'Montserrat-Bold.ttf'
        self.lbl1.font_size = 28
        self.ids.float_web.add_widget(self.lbl1)
        # URL Text Input
        self.web_input = TextInput(height=100)
        self.web_input.height = 100
        self.ids.float_web.add_widget(self.web_input)

As you can see I have tried affecting the size in two different locations, and it is still filling the entire window.

Body:
For the size property to take effect you need the size_hint property to be None on the corresponding axis:

class WebsiteInput(Screen):
    def __init__(self, **kwargs):
        super(WebsiteInput, self).__init__(**kwargs)
        Clock.schedule_once(self._finish_init)

    def _finish_init(self, dt):
        # Title Label
        self.lbl1 = Label(text="Enter a URL to bind to this button:",
                          pos=(self.x, self.height +132))
        self.lbl1.font_name = 'Montserrat-Bold.ttf'
        self.lbl1.font_size = 28
        self.ids.float_web.add_widget(self.lbl1)
        # URL Text Input
        self.web_input = TextInput(height=100,
                                   size_hint = (1,  None))
        self.ids.float_web.add_widget(self.web_input)


问:
How to put application/x-mpegURL in source in videojs
I'm not JavaScript guy but I have project with js and plugin VIDEOJS (Video.js v4.6.4 Copyright 2014 Brightcove, Inc. https://github.com/videojs/video.js/blob/master/).

I recived an error:

video.dev.js:1384 VIDEOJS: ERROR: (CODE:4 MEDIA_ERR_SRC_NOT_SUPPORTED)
  The video could not be loaded, either because the server or network
  failed or because the format is not supported.

I know that solved of this problem can be put: <source src="video/test.m3u8" type="application/x-mpegURL">. but my question is, how to do this.

答:
Original, but now outdated answer:

For browsers without native HLS support you need the videojs-contrib-hls plugin: http://videojs.github.io/videojs-contrib-hls/

As of Video.js v7, HLS is supported by default and does not require anything additional in the default build. HLS playback is either native (Safari, iOS) or Video.js's Media Source Extensions playback engine https://github.com/videojs/http-streaming, which replaced videojs-contrib-hls.